Home > Mobile >  Fibronacci sequence spitting wrong number
Fibronacci sequence spitting wrong number

Time:02-10

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

CodePudding user response:

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

CodePudding user response:

You are adding the num first Fibonacci numbers instead of the Fibonacci numbers less than or equal to num.

In my solution here, I do the correct thing and get the correct answer:

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