sum of even numbers in Fibonacci sequence

前端 未结 2 756
后悔当初
后悔当初 2021-01-29 15:38

I\'m trying to create a function to calculate the sum of only even numbers in Fibonacci sequence. How can I make this if/while loop to work?.

function fib() {
         


        
相关标签:
2条回答
  • 2021-01-29 16:18

    Replace while(x % 2) with while(x % 2 === 0). You're checking if x % 2 is true in your original while loop.

    0 讨论(0)
  • 2021-01-29 16:25

    function sumFibs(num) {
      let a = 1,
        b = 1,
        acc = 0;
    
      for (let i = 0; i < num - 2; i++) {
        let c = a;
    
        a += b;
        b = c;
    
        if (a % 2 === 0) {
          acc += a;
        }
      }
    
      return acc;
    }
    
    console.log(sumFibs(10)); // Logs out the even sum of the first 10 fabonacci sequence

    0 讨论(0)
提交回复
热议问题