The following code is displaying INF as the result. How can I fix it?
<?php
function fibonacci($n)
{
$a = 1;
$b = 1;
$result = 0;
for ($i = 0; $i < $n; $i=$i+1)
{
$sum = $a + $b;
$a = $b;
$b = $sum;
if ($a % 2 == 0)
{
$result =开发者_开发百科 $result + $a;
}
}
echo "<br/>" . $result;
}
echo fibonacci(400000);
?>
The number is too big to display, and INF is a pretty good guess :) (fibonacci(1000) gives you a number with 210 digits).
100: 22 digits, 110: 24 digits, 120: 25 digits, 130: 27 digits
If you extrapolate that, you would end up with about (400000 / 10) * 2 = 80000 digits.
The following implements your logic using bcmath to prevent the INF error.
function fibonacci($n)
{
$a = '1'; $b = '1'; $result = '0';
for ($i = 0; $i < $n; $i++) {
$sum = bcadd($a,$b);
$a = $b;
$b = $sum;
if (bcmod($a,'2') == '0') {
$result = bcadd($result,$a);
}
}
echo "<br />".$result;
}
As your fibonacci function doesn't actually return any value, there's no point in echo fibonacci(400000)
EDIT
However, your logic is completely flawed. The following should give you the correct result for the problem you're trying to solve (again using bcmath):
function fibonacci($n)
{
$a = '0'; $b = '1'; $sum = '0';
$sum = '0';
do {
$fib = bcadd($a,$b);
$a = $b;
$b = $fib;
if (bccomp($fib,$n) == -1) {
if (bcmod($fib,'2') == '0') {
$sum = bcadd($sum,$fib);
}
}
++$i;
} while (bccomp($fib,$n) == -1);
return $sum;
}
echo fibonacci(4000000);
Rather than simply executing it to get the result, look to see how it works and what it's actually doing
精彩评论