Created
May 12, 2022 23:58
-
-
Save blentz100/b55790f9edc2e30f69e5f4187e6b1c2f to your computer and use it in GitHub Desktop.
Problem 2: Even Fibonacci Numbers
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
//https://www.freecodecamp.org/learn/coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers | |
function fiboEvenSum(n) { | |
// write a fibo sequence generator | |
let fiboArr = [1,2] | |
for(let i=0; i < n; i++){ | |
fiboArr.push(fiboArr[i] + fiboArr[i+1]) | |
} | |
console.log(fiboArr) | |
let runningTotal = 0; | |
for(let j = 0; j < fiboArr.length;j++){ | |
if(fiboArr[j] % 2 == 0 && fiboArr[j] <= n){ | |
console.log(fiboArr[j]) | |
runningTotal = runningTotal + fiboArr[j] | |
} | |
} | |
// test and track even numbers | |
return runningTotal; | |
} | |
console.log(fiboEvenSum(10)) |
Spoiler warning: my solution
arr[arr.length - 1] and arr[arr.length - 2] represent the last and second to last numbers in the array
function fiboEvenSum(n) {
let sum = 0
let arr = [1, 2]
while (arr[arr.length - 1] <= n) {
if(arr[arr.length - 1] % 2 === 0) {
sum += arr[arr.length - 1]
}
arr.push(arr[arr.length - 1] + arr[arr.length - 2])
}
return sum;
}
@mabolen thanks for the spoiler alert! I haven't peeked yet, gonna tackle this later :)
function fiboEvenSum(n) {
let sum = 0
let arr = [1, 2]
let currentFibo = arr[arr.length - 1];
while (currentFibo <= n) {
currentFibo = arr[arr.length - 1];
let previousFibo = arr[arr.length -2];
if(currentFibo % 2 === 0) {
sum += currentFibo
}
arr.push(currentFibo + previousFibo)
}
return sum;
}
Refactored Marshall's solution to use some nicer variable names.
// This is the refactored version of the original solution we worked on during the first office hours.
function fiboEvenSum(n) {
// write a fibo sequence generator
let fiboArr = [1,2]
for(let i=0; (fiboArr[i] + fiboArr[i+1]) <= n; i++){
fiboArr.push(fiboArr[i] + fiboArr[i+1])
}
console.log(fiboArr)
let runningTotal = 0;
for(let j = 0; j < fiboArr.length;j++){
if(fiboArr[j] % 2 == 0 && fiboArr[j] <= n){
console.log(fiboArr[j])
runningTotal = runningTotal + fiboArr[j]
}
}
// test and track even numbers
return runningTotal;
}
console.log(fiboEvenSum(10))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems to give the correct answer but crashing the browser tab. ?