forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add way of computing fibonacci sequence by O(1) in Python3
- Loading branch information
Showing
1 changed file
with
20 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import math | ||
|
||
# The code below calculates N-th fibonacci number by O(1) | ||
# Such speed is achieved by using the Binet's formula which is | ||
# fib(n) = (phi^n - psi^n) / sqrt(5) | ||
# where | ||
# phi = (1 + sqrt(5)) / 2 and psi = (1 - sqrt(5)) / 2 | ||
# But in code we compute fib(n) as | ||
# fib(n) = round(phi^n) / sqrt(5) | ||
# because when n -> inf: abs(psi^n) -> 0 | ||
# When n is small this formula is innacurate because | ||
# we are computing in double and float and they aren't the exact values that we have in Math | ||
# Because of the same reasons we may have slightly innacurate values with small n. | ||
|
||
def fib(n): | ||
phi = (1 + math.sqrt(5)) / 2 | ||
return int(round(phi**n / math.sqrt(5))) | ||
|
||
n = 50 | ||
print(fib(50)) |