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

Seems to give the correct answer but crashing the browser tab. ?

@mabolen
Copy link

mabolen commented May 13, 2022

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;
}

@blentz100
Copy link
Author

@mabolen thanks for the spoiler alert! I haven't peeked yet, gonna tackle this later :)

@blentz100
Copy link
Author

blentz100 commented May 19, 2022

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;
} 

@blentz100
Copy link
Author

Refactored Marshall's solution to use some nicer variable names.

@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