Algorithm Scripting: Sum All Odd Fibonacci Numbers

Hello ,
I am trying to solve this issue.

" 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."

This was my solution, and I just can’t understand why it satisfies all the statements except the last one. I can’t find the mistake.
I would appreciate any help!

function sumFibs(num) {
  if(num === 1){
    return 1;
  }else if(num ===2){
    return 2;

let arr=[1,1],
curr =1,
prev =1;

for(let i = 2; i<num;i++){
  let next = curr + prev;
  prev = curr;
  curr= next;
  if(curr<num && curr%2!==0){

   return arr.reduce((a,b)=>a+b);

![Screenshot 2020-12-03 170937|559x500](upload://oa0YUvqj2MstfJv4VyvI4g4GIvS.jpeg) 


Just as a small hint to maybe point you in the right direction:

75025 is a Fibonacci number. How does your code handle situations where num is a valid Fibonacci number?


As long as that Fibonacci number satisfices the condition

curr<num && curr%2!==0

It will go ahead and push that number to the array for them be added with the other Fibonacci numbers that satisfy the condition.

I don’t know if I am missing something.

1 Like

Does it satisfy the condition?

If 75025 is the curr Fibonacci number and 75025 is also the value of num, will that condition evaluate to true?

1 Like

Of course I am missing something :

"…return the sum of all odd Fibonacci numbers that are less than or equal to num "

instead of curr<num && curr%2!==0 I should have use curr<=num && curr%2!==0 .

Before I was only including Fibonacci numbers that were less that num instead or less or equal.

Right @nhcarrigan ?

1 Like

That is correct, yes. :slight_smile:


Than you so much for your help!

I just spend my whole afternoon trying to figured this out.
I can’t believe how obvious the solution was.

But thank you for taking your time to help me see the light! :sweat_smile: