forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacci.php
64 lines (55 loc) · 1.41 KB
/
Fibonacci.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/**
* Fibonacci recursive
*
* @param int $num
* @return int
*/
function fibonacciRecursive(int $num)
{
/*
* Fibonacci series using recursive approach
*/
$fibonacciRecursive = [];
for ($i = 0; $i < $num; $i++) {
array_push($fibonacciRecursive, recursive($i));
}
return $fibonacciRecursive;
}
/**
* @param int $num
* @return int
*/
function recursive(int $num)
{
if ($num < 0) {
throw new \Exception("Number must be greater than 0.");
} else {
if ($num == 0 || $num == 1) {
return $num;
} else {
return recursive($num - 1) + recursive($num - 2);
}
}
}
function fibonacciWithBinetFormula(int $num)
{
/*
* Fibonacci series using Binet's formula given below
* binet's formula = ((1 + sqrt(5) / 2 ) ^ n - (1 - sqrt(5) / 2 ) ^ n ) ) / sqrt(5)
* More about Binet's formula found at http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section1
*/
$fib_series = [];
if ($num < 0) {
throw new \Exception("Number must be greater than 0.");
} else {
$sqrt = sqrt(5);
$phi_1 = (1 + $sqrt) / 2;
$phi_2 = (1 - $sqrt) / 2;
foreach (range(0, $num - 1) as $n) {
$seriesNumber = (pow($phi_1, $n) - pow($phi_2, $n)) / $sqrt;
array_push($fib_series, (int)$seriesNumber);
}
}
return $fib_series;
}