-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path002.js
55 lines (38 loc) · 1.7 KB
/
002.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Source: https://projecteuler.net/problem=2
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."
My Algorithm in words:
1. Make an array of fibonacci numbers with numbers from 1 to 4 million
2. Use a for loop on that array to extract the even numbers
3. Get the sum of the array with the even numbers
*/
function fibonacciUntil4Mil() {
let term1 = 1;
let term2 = 1;
let fibonacci = [1, 1];
let nextTerm = 2;
for (let i = 0; i <= 100; i++) { //The number 100 is kinda arbitrary
let nextTerm = term1 + term2; //next term is the sum of the last two numbers
term1 = term2; //shift term1 and term2 forward
term2 = nextTerm; //shift term1 and term2 forward
if (nextTerm < 4000000) { //push to the fibonacci numbers array until the terms reach 4,000,000
fibonacci.push(nextTerm);
}
}
return fibonacci; //return the array
}
function solution() {
let fibonacci = fibonacciUntil4Mil(); //get the fibonacci numbers array
let evenFibonacciNumbers = [];
for (let number of fibonacci) {
if (number % 2 === 0) { //check if the number is even by checking if the remainder when divided by 2 is 0
evenFibonacciNumbers.push(number); //if so, push it to the even fibonacci numbers array
}
}
const add = (a, b) => a + b; //arrow function to add numbers
return(evenFibonacciNumbers.reduce(add)); //add the numbers in the evenFibonacciNumbers array and return it
}
console.log(solution()); //outputs the answer!