Skip to content

Commit 05b887d

Browse files
Merge pull request #599 from CO18326/patch-1
fastfibonacci.py
2 parents 99c64a3 + bda2e59 commit 05b887d

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

Python/fastfibonacci.py

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,45 @@
1-
def fastfibonacci(i):
2-
if i<0:
3-
print("Incorrect input, enter number >= 0")
4-
elif i==0:
5-
return 0
6-
elif i==1:
7-
return 1
8-
else:
9-
return fastfibonacci(i-1)+fastfibonacci(i-2)
10-
11-
print(fastfibonacci(2))
1+
# the method relies on the fact that if we multiply matrix [[1,1],[1,0]] with it self n times we get nth fibonacci number at (0,0)
2+
#place
3+
# Fibonacci Series : 0,1,1,2............
4+
5+
# function that returns nth with 0 based indexing
6+
7+
def fastfibonacci(n):
8+
9+
f = [[1, 1],
10+
[1, 0]]
11+
if (n == 0):
12+
return 0
13+
power(f, n - 1)
14+
15+
return f[0][0]
16+
17+
def multiply(f, g):
18+
19+
a = (f[0][0] * g[0][0] + f[0][1] * g[1][0])
20+
s = (f[0][0] * g[0][1] + f[0][1] * g[1][1])
21+
d = (f[1][0] * g[0][0] + f[1][1] * g[1][0])
22+
h = (f[1][0] * g[0][1] + f[1][1] * g[1][1])
23+
24+
f[0][0] = a
25+
f[0][1] = s
26+
f[1][0] = d
27+
f[1][1] = h
28+
29+
30+
def power(f, n):
31+
32+
if( n == 0 or n == 1):
33+
return;
34+
g = [[1, 1],
35+
[1, 0]];
36+
37+
power(f, n // 2)
38+
multiply(f, f)
39+
40+
if (n % 2 != 0):
41+
multiply(f, g)
42+
43+
44+
45+

0 commit comments

Comments
 (0)