# Euler Project Problem 2 JavaScript

Posted on

Problem

Just solved Euler Project Problem 2 using JavaScript and I would like to know how I could improve my code. I do think it looks good, but you never know.

### Problem Statement

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.

``````function fibonacci() {
var a = 0, b = 1, count = 0;

for(var sum = 0; sum < 4000000;){

sum = a + b;

a = b;
b = sum;

if(sum % 2 == 0){
count += sum;
}
}
return count;
}

console.log(fibonacci());
``````

Solution

With a bit of fiddling I come to this code:

``````function fibonacci() {
let s = t = 0, a = 1, b = 2;
do {
s = a + b;
a = b;
b = s;
t += s & 1 ? 0 : s;
} while (s <= 4000000);
return t;
}

console.log(fibonacci());
``````

It is pretty much the same as yours with a few difference:

• I start with `a = 1, b = 2` as per instructions, but this means my result is 4613730 and not 4613732.
• `let` will do for the variables, because they are only used in the block they are in, but since that is the same as the function `var` is fine too.
• I also follow the instructions where it says to: “not exceed four million”, this includes four million.
• I prefer the clean look of the `do { ... } while` loop. This also means I don’t have to initialized the sum.
• There’s nothing wrong with your `(sum % 2 == 0)` check, but mine is visibly shorter. Normally I don’t care about that and would prefer yours because is easier to read.

I think the real art is to do this with less operations.