在解决了一个困扰了我一段时间的编程挑战后,我总是对自己想,“它有效,这已经足够好了”。
我不认为这真的是正确的心态,在我看来,我认为我应该始终尝试以最佳性能进行编码。
无论如何,话虽如此,我只是尝试了一个 ProjectEuler 问题。具体问题#2。
我怎么能改进这个解决方案。我觉得它真的很冗长。就像我在递归中传递前一个数字一样。
<?php
/* 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, ...
Find the sum of all the even-valued terms in the sequence which do not exceed
four million.
*/
function fibonacci ( $number, $previous = 1 ) {
global $answer;
$fibonacci = $number + $previous;
if($fibonacci > 4000000) return;
if($fibonacci % 2 == 0) {
$answer = is_numeric($answer) ? $answer + $fibonacci : $fibonacci;
}
return fibonacci($fibonacci, $number);
}
fibonacci(1);
echo $answer;
?>
请注意,这不是家庭作业。几百年前我离开了学校。我只是觉得无聊,正在处理 Project Euler 的问题