Skip to content

Commit 777ddca

Browse files
SandersLincclauss
andauthored
Update fast_fibonacci.py (#1889)
* Update fast_fibonacci.py * Update fast_fibonacci.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 0e6e505 commit 777ddca

File tree

1 file changed

+20
-27
lines changed

1 file changed

+20
-27
lines changed

dynamic_programming/fast_fibonacci.py

+20-27
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,37 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/env python3
22

33
"""
44
This program calculates the nth Fibonacci number in O(log(n)).
5-
It's possible to calculate F(1000000) in less than a second.
5+
It's possible to calculate F(1_000_000) in less than a second.
66
"""
77
import sys
8+
from typing import Tuple
89

910

10-
# returns F(n)
11-
def fibonacci(n: int): # noqa: E999 This syntax is Python 3 only
11+
def fibonacci(n: int) -> int:
12+
"""
13+
return F(n)
14+
>>> [fibonacci(i) for i in range(13)]
15+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
16+
"""
1217
if n < 0:
1318
raise ValueError("Negative arguments are not supported")
1419
return _fib(n)[0]
1520

1621

1722
# returns (F(n), F(n-1))
18-
def _fib(n: int): # noqa: E999 This syntax is Python 3 only
19-
if n == 0:
20-
# (F(0), F(1))
23+
def _fib(n: int) -> Tuple[int, int]:
24+
if n == 0: # (F(0), F(1))
2125
return (0, 1)
22-
else:
23-
# F(2n) = F(n)[2F(n+1) − F(n)]
24-
# F(2n+1) = F(n+1)^2+F(n)^2
25-
a, b = _fib(n // 2)
26-
c = a * (b * 2 - a)
27-
d = a * a + b * b
28-
if n % 2 == 0:
29-
return (c, d)
30-
else:
31-
return (d, c + d)
26+
27+
# F(2n) = F(n)[2F(n+1) − F(n)]
28+
# F(2n+1) = F(n+1)^2+F(n)^2
29+
a, b = _fib(n // 2)
30+
c = a * (b * 2 - a)
31+
d = a * a + b * b
32+
return (d, c + d) if n % 2 else (c, d)
3233

3334

3435
if __name__ == "__main__":
35-
args = sys.argv[1:]
36-
if len(args) != 1:
37-
print("Too few or too much parameters given.")
38-
exit(1)
39-
try:
40-
n = int(args[0])
41-
except ValueError:
42-
print("Could not convert data to an integer.")
43-
exit(1)
44-
print("F(%d) = %d" % (n, fibonacci(n)))
36+
n = int(sys.argv[1])
37+
print(f"fibonacci({n}) is {fibonacci(n)}")

0 commit comments

Comments
 (0)