Skip to content

Commit

Permalink
Create 002.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Walker30263 authored Aug 7, 2021
1 parent 1b00391 commit 97bf9ee
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions 002.js
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());

0 comments on commit 97bf9ee

Please sign in to comment.