-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1b00391
commit 97bf9ee
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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++) { | ||
let nextTerm = term1 + term2; | ||
term1 = term2; | ||
term2 = nextTerm; | ||
if (nextTerm < 4000000) { | ||
fibonacci.push(nextTerm); | ||
} | ||
} | ||
|
||
return fibonacci; | ||
} | ||
|
||
function solution() { | ||
let fibonacci = fibonacciUntil4Mil(); | ||
let evenFibonacciNumbers = []; | ||
|
||
for (let number of fibonacci) { | ||
if (number % 2 === 0) { | ||
evenFibonacciNumbers.push(number); | ||
} | ||
} | ||
|
||
const add = (a, b) => a + b; | ||
return(evenFibonacciNumbers.reduce(add)); | ||
} | ||
|
||
console.log(solution()); |