Skip to content

Commit ec9fdaa

Browse files
authored
Merge pull request TheAlgorithms#160 from kiandru/fastfibonacci
Added fastfibonacci.py
2 parents eb8375d + a07baad commit ec9fdaa

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

dynamic_programming/fastfibonacci.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
This program calculates the nth Fibonacci number in O(log(n)).
3+
It's possible to calculate F(1000000) in less than a second.
4+
"""
5+
import sys
6+
7+
8+
# returns F(n)
9+
def fibonacci(n: int):
10+
if n < 0:
11+
raise ValueError("Negative arguments are not supported")
12+
return _fib(n)[0]
13+
14+
15+
# returns (F(n), F(n-1))
16+
def _fib(n: int):
17+
if n == 0:
18+
# (F(0), F(1))
19+
return (0, 1)
20+
else:
21+
# F(2n) = F(n)[2F(n+1) − F(n)]
22+
# F(2n+1) = F(n+1)^2+F(n)^2
23+
a, b = _fib(n // 2)
24+
c = a * (b * 2 - a)
25+
d = a * a + b * b
26+
if n % 2 == 0:
27+
return (c, d)
28+
else:
29+
return (d, c + d)
30+
31+
32+
if __name__ == "__main__":
33+
args = sys.argv[1:]
34+
if len(args) != 1:
35+
print("Too few or too much parameters given.")
36+
exit(1)
37+
try:
38+
n = int(args[0])
39+
except ValueError:
40+
print("Could not convert data to an integer.")
41+
exit(1)
42+
print("F(%d) = %d" % (n, fibonacci(n)))

0 commit comments

Comments
 (0)