The Recursion That Cost Me a Full Stack Position

by | Jul 4, 2020 | 0 comments

The below code prints: 55 34 21 13 8 5 3 2 1
function printFibonacci(last, secondLast) {
  if ( last == 1 && secondLast == 0 ){
    return;
  }
  console.log(last);
  // Moving to the next fibonacci numbers
  return printFibonacci(secondLast, last - secondLast);
}
printFibonacci(55,34);

Solution:

The below code prints: 1 1 2 3 5 8 13 21 34 55
function printFibonacci(last, secondLast) {
  // The code above the recursive function call will be in descending order.
  if ( last == 1 && secondLast == 0 ){
    console.log(1);
    return;
  }

  // Recursive function call, Moving to the next fibonacci numbers
  printFibonacci(secondLast, last - secondLast);

  // The code below the recursive function call will be in ascending order.
  console.log(last);
}
printFibonacci(55,34);

We start from the last call (1,0), as seen in the image above, therefore printing the first Fibonacci value of the sequence (1) by hitting the stopping condition. Next, we go to the second function call (1,1) and print the second value of the sequence and so forth.

IF YOU GOT ANY VALUE SHARE 😄