Skip to content

Instantly share code, notes, and snippets.

@eday69
Last active June 15, 2018 17:55
Show Gist options
  • Save eday69/747ed638f13a4e58ad535850cebd078f to your computer and use it in GitHub Desktop.
Save eday69/747ed638f13a4e58ad535850cebd078f to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Sum All Odd Fibonacci Numbers
// Given a positive integer num, return the sum of all odd
// Fibonacci numbers that are less than or equal to num.
// The first two numbers in the Fibonacci sequence are 1 and
// 1. Every additional number in the sequence is the sum of
// the two previous numbers. The first six numbers of the
// Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
// For example, sumFibs(10) should return 10 because all odd
// Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.
function sumFibs(num) {
let fibo=[];
if (num > 0) fibo.push(1); // 1
if (num >= 1) fibo.push(1); // 2
if (num>2) {
while ((fibo[fibo.length-2] + fibo[fibo.length-1])<=num) {
fibo.push(fibo[fibo.length-2] + fibo[fibo.length-1]);
}
}
return fibo.filter(num => (num % 2) != 0).reduce((acum, num) => acum + num,0);
}
sumFibs(4); // 5
sumFibs(1000); // 1785
sumFibs(4000000); // 4613732
sumFibs(75024); // 60696
sumFibs(75025); // 135721
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment