Home > Enterprise >  Explain a code of finding nth Fibonacci Number
Explain a code of finding nth Fibonacci Number

Time:10-22

I am new to problem-solving. I found a code for finding the nth Fibonacci number. But I am confused about the work of some variables.

var fibonacci = function (n) {
  let prev = 0,
    cur = 1,
    temp;

  for (let i = 1; i < n; i  ) {
    temp = cur;
    cur = cur   prev;
    prev = temp;
  }

  return cur;
};

can you describe what the temp cur and prev variable is doing? especially the temp variable. Thank you!

CodePudding user response:

Basically Fibonacci numbers are the sum of the two previous Fibonacci numbers starting with two 1's.

Meaning, that the for loop cycles n times through the loop to get the nth Fibonacci number. All the code does is to store the (n-2)th number into a variable, the (n-1)th number into the second variable und calculating the nth number by adding (n-2)th (n-1)th.

After that it starts over with the (n-1)th being the (n-2)th and the nth being the (n-1)th.

CodePudding user response:

Don't feel bad, that code is quite difficult to follow. Here is a simpler version that uses new javascript features to avoid the temp variable:

function fib(n) {
  let prev = 0;
  let curr = 1;
  for(let i=1; i<n; i  ) {
    [prev, curr] = [curr, curr   prev];
  }
  return curr;
}

Or, without using the new javascript feature to allow swapping, it can be more clearly coded as follows:

function fib(n) {
  let prev = 0;
  let curr = 1;
  for(let i=1; i<n; i  ) {
    let next = curr   prev; 
    prev = curr; 
    curr = next;
  }
  return curr;
}

CodePudding user response:

temp means temporary, cur means current, prev means previous.

temp is needed because you have to assign cur as cur prev and at same time you need to assign prev as cur.

Without temp if you do cur = cur prev you won't be able to assign prev = cur because cur is already changed.

In other words to update cur you need prev and to update prev you need cur, with help of temp we can save old cur as temp and get new cur using old prev, and then using temp update prev.

here is an example:

if we have such values

let prev = 1,
    cur = 2,
    temp;

at loop we will do

temp = cur; // temp is 2
cur = cur   prev; // cur is 3
prev = temp; // prev is 2

if we were to do cur = cur prev; and prev = cur; then prev would be not 2 but 3 which is wrong.

  • Related