Hello, Everyone.
The second challenge of Project Euler looks a bit weird to me (description below).
“Problem 2: Even Fibonacci Numbers
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 n, find the sum of the even-valued terms.”
Why “fiboEvenSum(60)” should return 44, for example?
My code:
function fiboEvenSum(n) {
let fibos = [0, 1];
let evenFibos = [];
let sumOfEvenFibos = 0;
for (let k=1; k < n; k++) {
fibos.push(fibos[k] + fibos[k-1])
}
for (let j=0; j<fibos.length; j++) {
if ( fibos[j] % 2 != 0 && fibos[j] <= n) {
evenFibos.push(fibos[j])
sumOfEvenFibos += fibos[j]
}
}
console.log(fibos);
console.log(evenFibos);
console.log("Result:", sumOfEvenFibos)
return sumOfEvenFibos;
}
fiboEvenSum(60);
My output is:
[1, 1, 3, 5, 13, 21, 55]
Result: 99
Here, the 55 is included, since it’s smaller than n (which is 60 , in this case).
What am I missing here?
Any help is welcome.
Thanks!