Skip to main content

Command Palette

Search for a command to run...

Project Euler: #2 - Even Fibonacci numbers

Published
2 min read
Project Euler: #2 - Even Fibonacci numbers
S
I'm a frontend-heavy full stack developer who works with JavaScript, React, Next.js, TypeScript, and Node.js. ==== Currently Reworking my Blog ====

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

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,

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

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

The GitHub repo for this problem is found at 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.

Thank you!

More from this blog

T

The Introvert Coder | Quietly Building Loud Code!

23 posts

Quietly Building Loud Code!