JavaScript Implementation of Problem 2

View source code here on GitHub!

p0002()

Project Euler Problem 2

Moved the fibonacci optimization to javascript

Problem:

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.

Returns:

number --

 1/**
 2 * Project Euler Problem 2
 3 *
 4 * Moved the fibonacci optimization to javascript
 5 *
 6 * Problem:
 7 *
 8 * Each new term in the Fibonacci sequence is generated by adding the previous two
 9 * terms. By starting with 1 and 2, the first 10 terms will be:
10 *
11 * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
12 *
13 * By considering the terms in the Fibonacci sequence whose values do not exceed
14 * four million, find the sum of the even-valued terms.
15 *
16 * @return {number}
17 **/
18exports.p0002 = function() {
19// for a proof on why this formulation works, see python/p0002.py
20    let answer = 0;
21    let i = 2;
22    let j = 8;
23    let tmp = 0;
24    while (i < 4000000) {
25        answer += i;
26        tmp = 4 * j + i;
27        i = j;
28        j = tmp;
29    }
30    return answer;
31};

Tags: fibonacci-number, divisibility