Learning JavaScript with Project Euler #2
Project Euler: Problem #2
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 evenvalued terms.
Here is my solution:
/** * 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 * evenvalued terms. */ let a = 0, b = 1, temp = 0, sum = 0; while (a + b < 4000000) { temp = a + b; a = b; b = temp; if (temp % 2 === 0) { sum += temp; } } console.log(sum);
Explanation:
Firstly, I am using the code runner extension inside of vscode to run my solutions and print the answer in to my terminal. You could paste this code in to a code pen and observe the output in the console.
Step 1: Declare your variables.

I decided to start by creating my arithmetic variables (a, b, and temp) and the variable that will hold the final sum of all the even number in the fibonacci sequence less than or equal to four million.
 b gets initialized to 1 because the first number in the fibonacci sequence is 1.
 a is initialized to 0 because otherwise the sum of the two numbers would be greater than the first number in the sequence. That wouldn't make a difference in this specific problem, since we know we want the even numbers, but one iteration extra in this loop is okay.
Step 2: Iterate and find the sum of the evens

Next we loop while the sum of a and b is less than four million.
 During each loop we add a and b together and store the value in temp.
 Then we set a equal to the last fibonacci number (b), and then set b equal to the next number in the sequence (the sum of a and b).
 Lastly, we check if the next number we found is even, and if it is, we add it to the sum.
That's it! This one was just a simple arithmetic problem and didn't involve any fancy javascript functionality, but it's still good practice.
If you have any questions, please reach out in the comments below, at any of my socials, or at my email address.
Cheers!