An unbelievably new way to solve Fibonacci Challenge [Javascript]

David Kenechukwu Obi
2 min readFeb 24, 2022
inspired by my coding partner Henry

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.

one way to solve this

function sumFibs(num){

let a = 1;

let b = 1;

let oddSum = 1

while (b ≤ num){

if (b % 2 == 1){

sum +=b;

}

let temp = b;

b = a+b;

a = temp;

}

return oddsum;

}

now a solution without using a while loop.

function sumFibs(num){

const result = [0,1];

let oddSum = 1;

for (let i = 2; ; i++) {

let newFibNum = result[i-2]+ result[i-1];

if (newFibNum > num) {

break

}

result.push(newFibNum);

if(newFibNum % 2 !== 0) { oddSum += newFibNum

}

}

return oddSum;

}

This second method was inspired by Henry (my coding partner).

Thanks for reading.

--

--