Last active
May 4, 2020 19:42
-
-
Save mbadros/a92223bfecd4fb1cb5bfb1f41e5d1f4e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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