 # GoLang Programming for Fibonacci Numbers

Posted by

The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2   with seed values  F0 = 0 and F1 = 1. 

## Method 1 ( Use recursion )

Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential.

### output:-

Fibonacci Using Recursion

8

Run Program

## Method 2 ( Use Dynamic Programming )

Time Complexity: O(n)
Extra Space: O(n)

### output:-

Fibonacci Using Dynamic Programming
[0 1 1 2 3 5 8]

Run Program

## Method 3 ( Fibonacci Using Dynamic Programming and Space Optimization )

We can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series.

Time Complexity: O(n)
Extra Space: O(1)

### output:-

Fibonacci Using Dynamic Programming and Space Optimizion

0 1 1 2 3 5 8 13 21 34

Run Program

## Method 4 ( Using power of the matrix {{1,1},{1,0}} )

This is another O(n) which relies on the fact that if we multiply the matrix M = {{1,1},{1,0}}, n times to itself, (in other words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix.

Time Complexity: O(n)

Extra Space: O(1)

### output:-

Using power of the matrix {{1,1},{1,0}}

55

Run Program

## Method 5 ( Optimized Method 4 )

The method 4 can be optimized to work in O(Logn) time complexity. We can do recursive multiplication to get power(M, n) in the previous method

(Similar to the optimization done in this post).

Time Complexity: O(Logn)

Extra Space: O(Logn) if we consider the function call stack size, otherwise O(1)

### output:-

Using power of the matrix {{1,1},{1,0}}

34

Run Program

## Method 6 (O(Log n) Time)

Below is one more interesting recurrence formula that can be used to find the n’th Fibonacci Number in O(Log n) time.

If n is even then k = n/2:

F(n) = [2*F(k-1) + F(k)]*F(k)

If n is odd then k = (n + 1)/2

F(n) = F(k)*F(k) + F(k-1)*F(k-1)

Time complexity of this solution is O(Log n) as we divide the problem to half in every recursive call.