Skip to content

Instantly share code, notes, and snippets.

@RockfordWei
Created September 29, 2021 14:34
Show Gist options
  • Save RockfordWei/5b038372839dcc0eca8cf264e156c9ce to your computer and use it in GitHub Desktop.
Save RockfordWei/5b038372839dcc0eca8cf264e156c9ce to your computer and use it in GitHub Desktop.
fastest fibonacci precise calculation (to millionth) including negative
def fib(n):
if n == 0: return 0
if n == 1: return 1
if n >=2 and n % 2 == 0:
k = int(n / 2)
fbk = fib(k)
return (2 * fib(k - 1) + fbk) * fbk
if n >= 2:
k = int((n + 1) / 2)
fbk1 = fib(k - 1)
fbk2 = fib(k)
return fbk2 * fbk2 + fbk1 * fbk1
else:
x = 0; y = -1
for i in range(-n-1):
f = x + y
x = y; y = f
return f if n % 2 == 0 else -f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment