[SPOILERS] Build an Odd Fibonacci Sum Calculator

Everything work but i don’t like my solution if another have a advice or best solution please :ok_hand:

const sumFibs = (nbr) =>{ 
  let prev=0;
  let tmp=0; 
  let fib=1; 
  let sumOdd=1; 
  while(fib<=nbr){ 
    tmp=fib
    fib+=prev
    prev=tmp
    if (fib%2!==0) sumOdd+=fib 
    if (fib+prev>nbr) break
  } 
    return sumOdd 
} 

sumFibs(75025)

I’d use real words instead of abbreviations for variable names but that’s basically how I’d approach this.

Thank it’s a good advice :+1:

This looks good. +1 to using good names for the variables. Definitely makes it easier to debug when things go wrong. A couple of suggestions:

  • The break is redundant.
  • Updating fib before checking is slightly convoluted.

This is another way to do this:

const sumOddFibonacci = (limit) => {
if (limit < 1) return 0;

let current = 1;
let next = 1;
let oddSum = 0;

while (current <= limit) {
if (current % 2 !== 0) oddSum += current;
const newNext = current + next; // next Fibonacci number
current = next;
next = newNext;
}

return oddSum;
};