From 97bf9ee5adb9c57f43384b34850841becb787dc8 Mon Sep 17 00:00:00 2001 From: Walker30263 <64369095+Walker30263@users.noreply.github.com> Date: Sat, 7 Aug 2021 11:05:06 -0400 Subject: [PATCH] Create 002.js --- 002.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 002.js diff --git a/002.js b/002.js new file mode 100644 index 0000000..4ab5723 --- /dev/null +++ b/002.js @@ -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());