Skip to content

Instantly share code, notes, and snippets.

@blentz100
Created May 12, 2022 23:58
Show Gist options
  • Save blentz100/b55790f9edc2e30f69e5f4187e6b1c2f to your computer and use it in GitHub Desktop.
Save blentz100/b55790f9edc2e30f69e5f4187e6b1c2f to your computer and use it in GitHub Desktop.
Problem 2: Even Fibonacci Numbers
//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))
@blentz100
Copy link
Author

// 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