Created
June 10, 2021 12:23
-
-
Save BeanCounterTop/72b1c33074173c83dc3f92c0807b5691 to your computer and use it in GitHub Desktop.
Some handcrafted, artisanal n'th number Fibonacci finder functions
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
def fib1(n): | |
# Using array operations | |
fibArr = [0,1,1] | |
for i in range(0, n): | |
fibArr.pop(0) | |
fibArr.append(fibArr[0] + fibArr[1]) | |
return fibArr[0] | |
def fib2(n): | |
# Using a recursive inner function | |
fibArr = [0, 1, 1] # [last, current, iteration] | |
def fibme(myFibArr): | |
if n >= myFibArr[2]: | |
return fibme([ | |
myFibArr[1], | |
myFibArr[0] + myFibArr[1], | |
myFibArr[2] + 1] | |
) | |
else: | |
return myFibArr[0] | |
return fibme(fibArr) | |
def fib3(n): | |
# Using Binet's formula for the nth Fibonacci number (found here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html) | |
from math import sqrt | |
phi = (1 + 5 ** 0.5) / 2 | |
return int((phi**n - (phi*-1)**(n*-1))/sqrt(5)) # Binet's equation as implemented on python gives results that need deburring, e.g. 6765.000000000005 | |
format_spec = "{:>6}" * 4 | |
print(format_spec.format("n", "fib1", "fib2", "fib3")) | |
for i in range(0, 21): | |
print(format_spec.format(i, fib1(i), fib2(i), fib3(i))) | |
# Output: | |
# n fib1 fib2 fib3 | |
# 0 0 0 0 | |
# 1 1 1 1 | |
# 2 1 1 1 | |
# 3 2 2 2 | |
# 4 3 3 3 | |
# 5 5 5 5 | |
# 6 8 8 8 | |
# 7 13 13 13 | |
# 8 21 21 21 | |
# 9 34 34 34 | |
# 10 55 55 55 | |
# 11 89 89 89 | |
# 12 144 144 144 | |
# 13 233 233 233 | |
# 14 377 377 377 | |
# 15 610 610 610 | |
# 16 987 987 987 | |
# 17 1597 1597 1597 | |
# 18 2584 2584 2584 | |
# 19 4181 4181 4181 | |
# 20 6765 6765 6765 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment