又一个(Project Euler)Fibonacci问题:使用(vanilla)javascript,我试图将偶数加上<=给定限制:
首先,我的'if'语句出了问题,因为一些结果(如下)是错误的:
function fibonacciSum(limit) {
var limit = limit;
var series = [1,2];
var sum = 0;
var counter = 0;
for (var i=1; i<=33; i++) { // 33 is arbitrary, because I know this is more than enough
var prev1 = series[series.length-1];
var prev2 = series[series.length-2];
var newVal = prev1+prev2;
series.push(newVal);
counter ++;
console.log("series "+ counter + " is: " + series);
if (series[i] % 2 === 0 && series[i] <= limit) { // intending to sum only even values less than/equal to arbitrary limit
// sum = sum + series[i];
sum += series[i];
}
/*
var sum = series.reduce(function(a,b) {
/*
possible to filter here for even numbers? something like:
if (a %2 === 0)
*/
return a+b;
});
*/
console.log("SUM " + counter + ": " + sum);
} // for loop
} // fibonacci
fibonacciSum(4000000);
结果:
系列1是:1,2,3
SUM 1:2
系列2是:1,2,3,5
SUM 2:2
系列3是:1,2,3,5,8
SUM 3:2 //在这里寻找'10'
系列4是:1,2,3,5,8,13
SUM 4:10
系列5是:1,2,3,5,8,13,21
SUM 5:10
系列6是:1,2,3,5,8,13,21,34
SUM 6:10 //在这里寻找'44'
有人可以解释为什么这些都不按预期工作?
if (series[i] % 2 === 0) { ...
......或
if (series[i] % 2 === 0 && series[i] <= limit) { ...
其次,你可以看到我也尝试过使用series.reduce(......但是我无法想象如何只对偶数值求和;那是可行的/更干净的吗?
谢谢,
Whiskey T。
答案 0 :(得分:1)
不需要数组。使用三个变量来说斐波纳契序列中的前一个,当前和下一个数字。
我们也可以用2和3开始序列,因为没有其他偶数会影响结果。
我们将偶数的总和初始化为2,因为它是当前数字,它是偶数。在do...while
中,我们按顺序推进数字,如果新数字是偶数,我们将它们加到总和中。达到限制时停止。
function fibEvenSum(limit) {
var prev = 1,
current = 2,
next;
var sum = 2;
do {
next = prev + current;
prev = current;
current = next;
if (current >= limit)
break;
if (current % 2 == 0)
sum += current;
} while (true)
return sum;
}
可以使用奇数和偶数的属性来改进此算法:
odd + odd = even
even + even = even
even + odd = odd
答案 1 :(得分:0)
这对你有用......
var fibonacciSum = function(limit) {
var nMinus2 = 1, nMinus1 = 2, evensFound = [2], sum = nMinus1;
while (sum <= limit){
var n = nMinus1 + nMinus2;
if (n % 2 == 0){
sum += n;
if (sum > limit){
break;
}
evensFound.push(n);
}
nMinus2 = nMinus1;
nMinus1 = n;
}
console.log("Evens found - " + evensFound);
return evensFound;
};
var evensFound1 = fibonacciSum(4),
evensFound2 = fibonacciSum(10),
evensFound3 = fibonacciSum(60),
evensFound4 = fibonacciSum(1000);
$(evenResults).append(evensFound1
+ "<br/>" + evensFound2
+ "<br/>" + evensFound3
+ "<br/>" + evensFound4);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="evenResults"></div>
&#13;
答案 2 :(得分:0)
本着你所尝试的一种解决方案的解决方案 - 使用数组 - 尽管如此指出,它们并非必要。
var i = 0, sequence = [1, 2], total = 0;
while (sequence.slice(-1)[0] < 4000000) {
sequence.push(sequence.slice(-1)[0] + sequence.slice(-2)[0]);
}
for ( i; i <= sequence.length; i++ ) {
if ( sequence[i] % 2 === 0 ) {
total += sequence[i];
}
}