# Project Euler: #2 - Even Fibonacci numbers

### **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.

---

### **Problem Description**

A Fibonacci Sequence is a series in which each number is the sum of the two preceding ones.

> The sequence commonly starts from 0 and 1, although some authors start the sequence from 1 and 1 or sometimes (as did Fibonacci) from 1 and 2. Starting from 0 and 1, the first few values in the sequence are
> 
> `0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144`
> 
> ![A Fibonacci Sequence](https://cdn.hashnode.com/res/hashnode/image/upload/v1672205631476/09f42241-ebbe-475a-b73c-ab8d9702ee6c.png align="center")

In our problem, it is stated that the sequence starts with 1 and 2. And the first 10 terms would be, `1, 2, 3, 5, 8, 13, 21, 34, 55, 89.`

We want to find the Fibonacci sequence within 4 million and then find the sum of all the even numbers in that sequence.

---

### **Approach**

This problem can be approached using a `while` loop and solved using the mathematical formula,

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672649440431/2ae8381c-2335-4603-8e56-8d0c49c94ab7.png align="center")

We need to find the Fibonacci Sequence that starts with `1` and `2`, within 4 million. And our sequence looks like this, `1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... < 4000000`

Now, add the even numbers in the sequence, `2 + 8 + 34 + 144 + ...` which will be our result.

---

### Solution

```javascript
let fn_1 = 1, // first
    fn_2 = 2, // second
    sum = 0;

while (fn_1 < 4000000) {
    if (fn_1 % 2 === 0) sum += fn_1; 

    let fn = fn_1 + fn_2; 
    [fn_1, fn_2] = [fn_2, fn];
}
console.time('p#2');
console.log(sum);
console.timeEnd('p#2');
```

![Project Euler Problem #2 Solution](https://cdn.hashnode.com/res/hashnode/image/upload/v1672209994039/4227c1e1-3aff-460c-bdcc-605c8339010a.png align="center")

The GitHub repo for this problem is found at [02](https://github.com/sansk/project-euler-solutions-javascript/tree/main/02)

If you have another or a better solution, please leave it in the comments below.

For the other Project Euler Solutions, please follow the series [**Project Euler Solutions in JS.**](https://theintrovertcoder.hashnode.dev/series/project-euler)

Thank you!
