-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path002JS-even-fibonacci-numbers.js
38 lines (28 loc) · 1.04 KB
/
002JS-even-fibonacci-numbers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 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.
//////////////////////////////////////////////////////////
// Approach:
// the nth term equals the sum of terms n-1 and n-2
// the 0th term is 1, the 1st is 2 (unusual, but it's how
// the problem is stated)
// thus, there is a cycle of odd-even-odd, odd-even-odd, etc.
// so we need the sum of every third term, starting at the
// 1st (4th, 7th, 10th, etc), and continuing until the value
// is over 4 million. (2 + 8 + 34 + 144 + .....)
function sumEvenFibonacciNums(cap) {
const values = [1, 2];
let sum = 0;
for (let i = 1; values[i] <= cap; i++) {
values[i + 1] = values[i] + values[i - 1];
if ((i - 1) % 3 === 0) {
sum += values[i];
}
}
return sum;
}
console.log(sumEvenFibonacciNums(144));