斐波那契数列吐出错误的数字

Fibronacci sequence spitting wrong number

我创建了一个函数,可以将所有奇数斐波那契数相加到给定的数字,并且在大多数情况下,它适用于除一个数字以外的所有数字。例如 sumFibs(10) 应该 return 10 因为所有 Fib #s <= 10 是 1,1,3 和 5.

如果我做 sumFibs(75024);我得到的是 135721,而不是预期值 60696。对于其他所有数字,它都能完美运行,我正在抓耳挠腮地解决它

function sumFibs(num) {

  let thunderAss = [];
  let currDmp = 0;
  let nxtRmp = 1;
  var pushNxt = 0;
  // push into array
  for (let x = 0; x < num; x++) {
    if (x <= 1) {
      console.log("lets go");
      thunderAss.push(1); // 2l almond milk
    } else {
      thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
      console.log(x, " x is factor");
    }
  }
  console.log(thunderAss);

  let cuntNuts = 0;
  for (let x = 0; x < num; x++) {
    if (cuntNuts < num) {
      if (thunderAss[x] % 2 == 0) {} else {
        cuntNuts += thunderAss[x];
      }
    } else {
      break;
    }
  }
  console.log("CN: ", cuntNuts);
  return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);

您添加的是第 num 个斐波那契数,而不是小于或等于 num 的斐波那契数。

在我的解决方案中,我做了正确的事情并得到了正确的答案:

function* fibonacci()
{
    let x = 0;
    let y = 1;

    while (true) {
        yield x;
        [x, y] = [y, x+y];
    }
}


function sum_odd_fibonacci(max)
{
    const fib_seq = fibonacci();

    let s = 0;
    let n;
    while ( (n=fib_seq.next().value) <= max) {
        if (n % 2 == 1) {
            s += n;
        }
    }

    return s;
}


console.log(sum_odd_fibonacci(75024));

条件if (cuntNuts < num)错误。 cuntNuts 是斐波那契数列之和,而不是斐波那契数列本身。所以你在总和达到 n 时停止,而不是将所有奇数相加到 n.

您应该将 thunderAss[x]num 进行比较。如果该数字应包含在总数中,则应为 <=

您也可以将此条件放入 for 循环 header 而不是将其作为单独的检查添加到 body.

function sumFibs(num) {

  let thunderAss = [];
  let currDmp = 0;
  let nxtRmp = 1;
  var pushNxt = 0;
  // push into array
  for (let x = 0; x < num; x++) {
    if (x <= 1) {
      console.log("lets go");
      thunderAss.push(1); // 2l almond milk
    } else {
      thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
      console.log(x, " x is factor");
    }
  }
  console.log(thunderAss);

  let cuntNuts = 0;
  for (let x = 0; thunderAss[x] <= num; x++) {
    if (thunderAss[x] % 2 == 0) {} else {
      cuntNuts += thunderAss[x];
    }
  }
  console.log("CN: ", cuntNuts);
  return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);