FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
TheAlgorithms-Python/dynamic_programming/fast_fibonacci.py at master · windNight/TheAlgorithms-Python · GitHub
windNight
/
TheAlgorithms-Python
Public
forked from
TheAlgorithms/Python
Notifications
You must be signed in to change notification settings
Fork
1
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
TheAlgorithms-Python
/
dynamic_programming
/
fast_fibonacci.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
38 lines (29 loc) · 864 Bytes
Breadcrumbs
TheAlgorithms-Python
/
dynamic_programming
/
fast_fibonacci.py
Copy path
File metadata and controls
38 lines (29 loc) · 864 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
"""
This program calculates the nth Fibonacci number in O(log(n)).
It's possible to calculate F(1_000_000) in less than a second.
"""
from
__future__
import
annotations
import
sys
def
fibonacci
(
n
:
int
)
->
int
:
"""
return F(n)
>>> [fibonacci(i) for i in range(13)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
"""
if
n
<
0
:
raise
ValueError
(
"Negative arguments are not supported"
)
return
_fib
(
n
)[
0
]
# returns (F(n), F(n-1))
def
_fib
(
n
:
int
)
->
tuple
[
int
,
int
]:
if
n
==
0
:
# (F(0), F(1))
return
(
0
,
1
)
# F(2n) = F(n)[2F(n+1) − F(n)]
# F(2n+1) = F(n+1)^2+F(n)^2
a
,
b
=
_fib
(
n
//
2
)
c
=
a
*
(
b
*
2
-
a
)
d
=
a
*
a
+
b
*
b
return
(
d
,
c
+
d
)
if
n
%
2
else
(
c
,
d
)
if
__name__
==
"__main__"
:
n
=
int
(
sys
.
argv
[
1
])
print
(
f"fibonacci(
{
n
}
) is
{
fibonacci
(
n
)
}
"
)
Back
|
FazBrowse Home
|
New Git URL