1
+ '''
2
+ This algorithm calculates the Nth Fibonacci Nummber in log(N) time complexity
3
+ The key idea behind this algorimth is to use matrix exponentiation technique (matrix multiplication + binary exponentiation)
4
+ This algorithm uses the fact that the Fibonacci Numbers can be converted to a 2D matrix of 2x2 size, [[1, 1][1, 0]], and the Fibonacci
5
+ Number which is to be calculated with the help of matrix multiplication will be nothing but cell, (0,0) of (Matrix)^n ,i.e, our resultant
6
+ matrix.
7
+ '''
8
+ def fib (n ):
9
+
10
+ F = [[1 , 1 ],
11
+ [1 , 0 ]]
12
+ if (n == 0 ):
13
+ return 0
14
+ power (F , n - 1 )
15
+
16
+ return F [0 ][0 ]
17
+
18
+ '''
19
+ Matrix multiplication is calculated using Strassen Algorithm which calculates the product of Two Matrices in o(N^3) time complexity.
20
+ Since, the size of matrix here is fixed, i.e, 2x2, so, the Time Complexity will be O(1).
21
+ '''
22
+ def multiply (F , M ):
23
+
24
+ x = (F [0 ][0 ] * M [0 ][0 ] +
25
+ F [0 ][1 ] * M [1 ][0 ])
26
+ y = (F [0 ][0 ] * M [0 ][1 ] +
27
+ F [0 ][1 ] * M [1 ][1 ])
28
+ z = (F [1 ][0 ] * M [0 ][0 ] +
29
+ F [1 ][1 ] * M [1 ][0 ])
30
+ w = (F [1 ][0 ] * M [0 ][1 ] +
31
+ F [1 ][1 ] * M [1 ][1 ])
32
+
33
+ F [0 ][0 ] = x
34
+ F [0 ][1 ] = y
35
+ F [1 ][0 ] = z
36
+ F [1 ][1 ] = w
37
+
38
+ '''
39
+ Power function uses Binary Exponentiation Technique to calculate the value of x^n in O(logN) time instead of O(N) time.
40
+ '''
41
+ def power (F , n ):
42
+
43
+ if (n == 0 or n == 1 ):
44
+ return
45
+ M = [[1 , 1 ],
46
+ [1 , 0 ]]
47
+
48
+ power (F , n // 2 )
49
+ multiply (F , F )
50
+
51
+ if (n % 2 != 0 ):
52
+ multiply (F , M )
53
+
54
+
55
+ # Driver Code
56
+ if __name__ == "__main__" :
57
+ n = 5
58
+ print (fib (n ))
59
+
60
+ '''
61
+ I hope you have a fun time reading this algorithm.
62
+ Problems for practice:
63
+ https://practice.geeksforgeeks.org/problems/generalised-fibonacci-numbers1820/1
64
+ https://practice.geeksforgeeks.org/problems/nth-fibonacci-number1335/1
65
+ https://practice.geeksforgeeks.org/problems/37f36b318a7d99c81f17f0a54fc46b5ce06bbe8c/0
66
+ '''
0 commit comments