sum of the odd terms of the fibonacci sequence code example
Example 1: sum all odd fibonacci numbers
function sumFibs(num) {
var prevNumber = 0;
var currNumber = 1;
var result = 0;
while (currNumber <= num) {
if (currNumber % 2 !== 0) {
result += currNumber;
}
currNumber += prevNumber;
prevNumber = currNumber - prevNumber;
}
return result;
}
sumFibs(4);
Example 2: sum all odd fibonacci numbers
const sumFibs = num => {
const fibNum = [1,1]
const fibOdd = [1,1]
for(let i = 0; i < num; i++){
const fibAdd = fibNum[i] + fibNum[fibNum.length - 1]
if(fibAdd > num) break;
fibNum.push(fibAdd)
if(fibAdd % 2 !== 0) fibOdd.push(fibAdd)
}
return fibOdd.reduce((acc,cur) => acc + cur)
}
sumFibs(75024);