Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:58
Show Gist options
  • Save rfprod/95117846800bea2e0ac9 to your computer and use it in GitHub Desktop.
Save rfprod/95117846800bea2e0ac9 to your computer and use it in GitHub Desktop.
Sum All Odd Fibonacci Numbers
function sumFibs(num) {
var init = 0;
var fib = [0,1];
var fibSum = 0;
var nextFib = 0;
var getFib = 0;
var i = 2;
while (nextFib <= num){
getFib = fib[i-2]+fib[i-1];
if (getFib <= num){
fib.push(getFib);
}
nextFib = fib[i-1]+fib[i];
i++;
}
for (var j=0;j<fib.length;j++){
if (isEven(fib[j]) === false){
fibSum = fibSum+fib[j];
}
}
function isEven(n){
n = Math.abs(n%2);
if (n == 1){
return false;
}else{
return true;
}
return false;
}
return fibSum;
}
sumFibs(75025);

Sum All Odd Fibonacci Numbers

Returns the sum of all odd Fibonacci numbers up to and including the passed number if it is a Fibonacci number. The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8, and each subsequent number is the sum of the previous two numbers. As an example, passing 4 to the function should return 5 because all the odd Fibonacci numbers under 4 are 1, 1, and 3.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment