Skip to content

Instantly share code, notes, and snippets.

@boboben1
Created August 12, 2021 16:37
Show Gist options
  • Save boboben1/3333338703418fdb56ad6747419c5951 to your computer and use it in GitHub Desktop.
Save boboben1/3333338703418fdb56ad6747419c5951 to your computer and use it in GitHub Desktop.
Fast Fib Using Exponentiation by Squaring and Binets Algorithm using only integers
# Combined Exponentiation by Squaring and Binet's Algorithm. Encoded as a + b sqrt(5). Phi**n - phi**n = 0 + 2 (Phi**n)_b sqrt(5)
def fast_fib(n):
n -= 1
a, b, r, s = 1, 1, 1, 1
while 1:
if n & 1 == 1:
r, s = a*r+5*b*s >> 1, a*s+b*r >> 1
n >>= 1
if n == 0:
break
a, b = a*a+5*b*b >> 1, a*b
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment