The Fibonacci sequence in Javascript

JavascriptData Structure AlgorithmsFront End Technology

Fibonacci numbers are the numbers such that every number in the series after the first two is the sum of the two preceding ones. The series starts with 1, 1. Example −

1, 1, 2, 3, 5, 8, 13, 21, 34, ….

We can write a program to generate nth as follows −

functionfibNaive(n) {
   if (n<= 1) return n;
   returnfibNaive(n - 1) + fibNaive(n - 2);
}

You can test this using −

console.log(fibNaive(7));
console.log(fibNaive(8));
console.log(fibNaive(9));
console.log(fibNaive(4));

This will give the output −

13
21
34
3

Let us look at how these function calls are actually happening −

/**
* f(5)
* / \
* f(4) f(3)
* / \ / \
* f(3) f(2) f(2) f(1)
* / \ ..........
* f(2) f(1)..........
*/

When we make a call to f(5), we will be calling f(2) nearly 4 times and it'll run the same code over and over 4 times. This is a case of an overlapping subproblem. Try running that function for 500. You'll be stuck as all these calls will take loads of time.

When we need the 5th Fibonacci number, we just need the lower Fibonacci numbers once but we compute them a lot more times than that. We can reduce this redundant computation if we just store the computed values somewhere instead. This is the crux of dynamic programming.

Compute once and reuse later.

Let's look at an memorized implementation of the fib function.

letfibStore = {};
functionfibDP(n) {
   if (n<= 1) return n;
if (fibStore[n]) {
   returnfibStore[n];
}
   fibStore[n] = fibDP(n - 1) + fibDP(n - 2);
   returnfibStore[n];
}

Now we're using a store, fibStore to keep track of values we've already computed. This reduces the excessive redundant computations and keeps the function efficient.

You can test this using −

console.log(fibDP(7));
console.log(fibDP(8));
console.log(fibDP(9));
console.log(fibDP(4));

This will give the output −

13
21
34
3

You can even test this for huge values.

raja
Updated on 22-Jun-2020 15:00:49

Advertisements