Fibonacci in Javascript

Masum Billah
3 min readSep 18, 2022

--

Fibonacci pattern

The Fibonacci Sequence is a series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 … The next number is found by adding up the two numbers before it

For example

The next number is found by adding up the two numbers before it:

  • the 2 is found by adding the two numbers before it (1+1),
  • the 3 is found by adding the two numbers before it (1+2),
  • the 5 is (2+3),
  • and so on!
Fibonacci Series
1 + 0 = 1
1 + 1 = 2
2 + 1 = 3
3 + 2 = 5
5 + 3 = 8
8 + 5 = 13
13+ 8 = 21
21+ 13= 34 etc

Now we know how the sequence is incremented. Let’s think about it, is there any pattern between those numbers? Well the answer is yes and that is 1.6

Fibonacci in hand

What is Golden Ratio and What is 1.6?

The Fibonacci sequence and the golden ratio appear in our world in diverse forms. From human DNA strands to the Milky Way Galaxy, the proportions described in the golden ratio are seemingly everywhere. The golden ratio shows up in some inanimate natural phenomena

Got it what can I do with that sequence? Yes, we have a sequence that we can get by dividing two numbers like below

5 ÷  3  = 1.6
8 ÷ 5 = 1.6
13 ÷ 8 = 1.625
21 ÷ 13 = 1.615
34 ÷ 21 = 1.619
55 ÷ 34 = 1.6176
89 ÷ 55 = 1.61818
Golden Ratio

So, The Golden Ratio is : 1.618033

Now, it’s time to solve the problem by Javascript. As we know we have to add last two numbers, So let’s write a while loop.

It will a very simple step to go further by calling it small number. But when we will call this function with a big number then obviously it would be a performance issue. We can solve fibonacci problem by mathematics as we know the Golden Ration or 1.6

function fib(n) {
return Math.pow(1.618, n) / Math.sqrt(5);
}

fib(100); //353481529465431400000

Try to find out the value of phi or we can say the golden ratio

let phi = (1 + Math.sqrt(5))/2;
console.log(phi) // 1.618

So, the complete example would be like below.

function fib(n) {
let phi = (1 + Math.sqrt(5))/2;
let asymp = Math.pow(phi, n) / Math.sqrt(5);

return Math.round(asymp);
}

fib(1000); // 4.346655768693734e+208 in just a few milliseconds

--

--