Skip to content

Instantly share code, notes, and snippets.

@mbadros
Last active May 4, 2020 19:42
Show Gist options
  • Select an option

  • Save mbadros/a92223bfecd4fb1cb5bfb1f41e5d1f4e to your computer and use it in GitHub Desktop.

Select an option

Save mbadros/a92223bfecd4fb1cb5bfb1f41e5d1f4e to your computer and use it in GitHub Desktop.
def fib(n):
v1, v2, v3 = 1, 1, 0 # initialise a matrix [[1,1],[1,0]]
for rec in bin(n)[3:]: # perform fast exponentiation of the matrix (quickly raise it to the nth power)
calc = v2*v2
v1, v2, v3 = v1*v1+calc, (v1+v3)*v2, calc+v3*v3
if rec=='1': v1, v2, v3 = v1+v2, v1, v2
return v2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment