[SOLVED] Fibronacci sequence spitting wrong number

Issue

I have created a function that sumbs up all odd fibronacci numbers up to a given number, and for the most part it works all for except one number. For example sumFibs(10) should return 10 becuz all Fib #s <= 10 are 1,1,3 and 5.

If I do sumFibs(75024); I get 135721 instead of the expected value is 60696. For every other number it works perfectly and am scratching my head to solve it

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);

Solution

The condition if (cuntNuts < num) is wrong. cuntNuts is the sum of fibonacci numbers, not the fibonacci number itself. So you’re stopping when the sum reaches n, not summing all the odd numbers up to n.

You should be comparing thunderAss[x] with num. And it should be <= if that number should be included in the total.

You can also put this condition into the for loop header rather than adding it as a separate check in the 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);

Answered By – Barmar

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.