DEV Community

Cover image for Project Euler Problem 2 - Fibonacci Question
KenjiGoh
KenjiGoh

Posted on • Updated on

Project Euler Problem 2 - Fibonacci Question

Hi All! This is my first post here! I shall share a short post on the solution to the Fibonacci Problem by Project Euler. This is considered a common beginner level question to practice basic 'for loop'.

The Question is as such:

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.

Posting my solution (in JavaScript) here for sharing!

let n1 = 0,
  n2 = 1,
  nextNum,
  fiboSum = 0,
  fiboArr = [];

for (let i = 1; i <= 100; i++) {
  // console.log(n1); //keep logging new n1
  fiboArr.push(n1);
  nextNum = n1 + n2; //get nextNum
  n1 = n2; //update prev n2 as new n1
  n2 = nextNum; //update nextNum as new n2
}
//console.log(fiboArr);

for (let i of fiboArr) {
  if (i % 2 === 0 && i < 4000000) {
    console.log(i);
    fiboSum = fiboSum + i;
  }
}
console.log(`Sum of even-valued terms: ${fiboSum}`);

Enter fullscreen mode Exit fullscreen mode

You will see this in your terminal:

0
2
8
34
144
610
2584
10946
46368
196418
832040
3524578
Sum of even-valued terms: 4613732
Enter fullscreen mode Exit fullscreen mode

For those interested to solve more challenging questions, you may refer to this link for more questions. Click Here. Cheers!

Discussion (0)