Fibonacci序列中偶数的总和

时间:2014-03-02 19:58:16

标签: javascript

我正在尝试创建一个函数来计算Fibonacci序列中只有偶数的和。如何使这个if / while循环起作用?。

function fib() {
  var x, y, total;
  for (var i = 0; i < 10; i++) {
    if (i === 0) {
      x = 1;
      y = 2;
    }

    while( x % 2) {
      total = x + y;
      x = y;
      y = total;
    }

    return(total);
  }
};

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 1 :(得分:0)

while(x % 2)替换为while(x % 2 === 0)。您正在检查原始while循环中x % 2是否为真。