php - Fibonacci series optimisation
How can i optimise this ? Am getting timeout error when i executes this I am trying to execute this on my wampserver on a windows 10. This code is actually that i wrote for a test but the test fails if i get the values of $a and $b as huge.
Any help will be welcome. Thank you.
* @param $n
* @param false $offset
* @param false $injectResult
* @return int|mixed
*/
Seems that this part is the worm
function fibonacci($n, $offset = false, $injectResult = false)
{
if ($offset == $n && $injectResult) {
return $injectResult;
}
if ($n == 0) {
return 0;
}
if ($n == 1) {
return 1;
}
if ($n > 1) {
return fibonacci($n - 1) + fibonacci($n - 2);
}
}
/**
* Function to sum the fibonacci series result
* @param $a
* @param $b
* @return float|int
*/
This part seems ok
function sumFibonacci($a, $b)
{
$diff = $b - $a;
$result = [];
for ($i = 0; $i <= $diff; $i++) {
if ($i == 0) {
$result[$i] = fibonacci($a);
} else {
$result[$i] = fibonacci($a + $i, $a - ($i - 1), $result[$i - 1]);
}
}
return array_sum($result);
}
// Example of how to use it
echo sumFibonacci(38,58);
/**
* How can i optimise this if $a = 38 $b= 58 e.g sumFibonacci(38,58);
*/ ```
Answer
Solution:
I solved it by modified the function to be non recursive
{
$numnar1 = 0;
$numnar2 = 1;
$count = 0;
$result='';
while ($count < $numnar) {
$result = $numnar1;
$numnar3 = $numnar2 + $numnar1;
$numnar1 = $numnar2;
$numnar2 = $numnar3;
$count++;
}
return $result;
}
Source