Fibonacci challenge

If you are starting at 0, then fib1 should be 0. But the challenge linked specifically is starting with 1,1

Yup. With that and a while loop you can make all the fibs you want. Now you need to put the pieces together and add in a way to sum up the odd values you make.

There are details to sort out, but you have the bones of a solution here.

i think if you try to start with 0, it would be 0+0 and the result will constantly be 0 except you iterate one of the variables to 1, then i guess that might work.

function sumFibs(num) {
  let fib1 = 1;
  let fib2 = 1;
  let fib3 = fib1 + fib2;
  while (fib2 <= num){
    fib1 = fib2;
    fib2 = fib3
  }
  return num;
}

sumFibs(4);

this is telling me that i will have a potential infinite loop

You can either start with 0,1 or 1,1. Not 1,0.

0,1,1,2,3,5,8
Or
1,1,2,3,5,8
Not
1,0,1,1,2,3,5,8

1 Like

You need to increment fib3 in the loop too. Otherwise fib2 never changes.

function sumFibs(num) {
  let fib1 = 1;
  let fib2 = 1;
  let fib3 = fib1 + fib2;
  let sum = 0;
  while (fib2 <= num){
if (fib2 % 2 == 1){
  sum+=fib2;
}
    fib1 = fib2;
    fib2 = fib3;
    fib3 = fib1 + fib2
  }
  return sum;
}

console.log(sumFibs(4));

see my final code. my answer is 1 less than the correct answer

you’re very correct, 0,1 not 1,0.

i now set my fib1 = 0 and it worked. thank you all for your help

Huzzah, good work getting it figured out!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.