1
votes

I am new to JavaScript, for some reason my Fibonacci Sequence Generator. What is a Fibonacci Sequence, easy, it is a sequence that takes the last two numbers of the sequence and adds them to create the next number. Here is an example. 0, 1, 1, 2, 3, 5, 8, 13, 21... I tried to make a loop with a while statement in which the variable that was once the first number (in this case 0), converts into a new number which is whatever that number was plus the second number (in this case 1). example: var firstNumber(which is 0) + var secondNumber(which is 1) = var firstNumber(which no equals to 1 because we added 0 + 1). If this goes on in a loop, then, in theory, it could go infinitely adding the last number and the one before it, and making that second to last number making the result of the addition. Here is my code, it is not working at all. Any help would be deeply appreciated. Hopefully, I have explained my self correctly.

var firstNumber = 0;
var secondNumber = 1;

function fibonacciGenerator(n){
    while (secondNumber <= n){
        firstNumber + secondNumber == firstNumber;
        secondNumber + firstNumber == secondNumber;
    }
}
console.log(fibonacciGenerator(50));
2

2 Answers

0
votes

firstNumber + secondNumber == firstNumber; this is not the way to assign a value to a variable

and you need to add a return statement at the end of your function.

Does this help ?

var firstNumber = 0;
var secondNumber = 1;

function fibonacciGenerator(n){
  while (secondNumber <= n){
      firstNumber = firstNumber + secondNumber;
      secondNumber = secondNumber + firstNumber;
  }
  return secondNumber
}

console.log(fibonacciGenerator(50));
0
votes

You need to assign a third variable to store the sum of the first and second variable each iteration after that you should make your loop starts from 2, not 1 because you already assing it before the loop staring, another thing when you assign a value from variable to another it works from right side to left side so it should be like this

 firstNumber = firstNumber + secondNumber;
 secondNumber = secondNumber + firstNumber;

so after editing it would be like this

function fibonacciGenerator(n) {
    var a = 0,
        b = 1,
        c;

    for (let i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return b;
}
console.log(fibonacciGenerator(9))

to read more about it check this link