来自 Project Euler with PHP 的斐波那契问题 #2
问题是这样的:
斐波那契数列中的每一项新项都是通过添加前两项而生成的。 >从 1 和 2 开始,前 10 项将是:
1、2、3、5、8、13、21、34、55、89、...
考虑斐波那契数列中值不超过四百万的项,>求偶数项的总和。
这是我用 PHP 编写的,
<?php
function fibo($first, $second, $limit){
$next = $first + $second;
if ($next % 2 ==0) {
$array[]= "$next";
}
do
{
fibo($second,$next, $limit);
} while ($next < $limit);
$sum=array_sum($array[]);
echo "$sum";
}
fibo(1,2,4000000);
?>
但我的代码无法运行...任何人都可以帮忙吗?
The question goes like this:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By >starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, >find the sum of the even-valued terms.
And this is what I wrote in PHP
<?php
function fibo($first, $second, $limit){
$next = $first + $second;
if ($next % 2 ==0) {
$array[]= "$next";
}
do
{
fibo($second,$next, $limit);
} while ($next < $limit);
$sum=array_sum($array[]);
echo "$sum";
}
fibo(1,2,4000000);
?>
My code doesn't run though...can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将
$sum=array_sum($array[]);
更改为$sum=array_sum($array);
并看看会发生什么......另外,当你有遇到问题时,最好让其他人知道它是什么类型的问题。就像错误消息或类似的东西......
如果万一没有 错误已报告,请尝试将其打开。
编辑:
我记得在递归解决一些欧拉问题时,我碰巧遇到了页面崩溃的问题。 这可能是由于某些递归限制而发生的 。我相信这与你的问题类似。
Try changing
$sum=array_sum($array[]);
to$sum=array_sum($array);
and see what it happens...Also, when you have a problem, it's good to let the others know what kind of problem it is. Like the error message or something like that...
If by any chance there are no errors reported, try to turn them on.
EDIT:
I remember that when solving some Euler problems recursively I happened to have a problem where the page crashed. This may happen due to some recursion limitations. I believe it's similar to your problem.
这是一个简单的范围问题。您在函数中定义
$array
,不能在外部使用它。尝试使用全局数组:您将能够在外部使用它。
It's a simple scope problem. You define
$array
in the function, you can't use it outside. Try using a global array:You will be able to use it outside.