简体   繁体   中英

Algorithm Scripting: Sum All Odd Fibonacci Numbers

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){
      arr.push(curr);    
  }
}

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

console.log(sumFibs(75024));
console.log(sumFibs(75025));

It's giving me the same result for both even when they should be different.

在此处输入图像描述

You are supposed to add numbers that are "less or equal to num". You are summing only numbers < num.

The mistake appears to be the conditional statement if(curr<num && curr%2!==0) which does't satify the instructions above which say as follows: return the sum of all odd Fibonacci numbers that are less than or equal to num

Therefore when we use if(curr<num && curr%2!==0) as our conditional statement we do not include 75025 since it doesn't represent a number less than the variable num.

That is where we find the mistake. It should include numbers that are not only less but also the ones that are equal to num , in this case num being 75025, which wasn't being include in the group of odd Fibonacci numbers to sum up, due to the incorrect conditional statement.

You are only considering numbers less than num, but the task description says less than or equal. The base case for 1 is also wrong. Actually you don't need the base cases at the beginning. And instead of the for loop you should use a while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM