Created
December 19, 2017 21:33
-
-
Save cjtallman/b425505709e8012946e2d0d769dd29ac to your computer and use it in GitHub Desktop.
Fast Fibonacci
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
local function matmul(a, b) | |
return { | |
a[1]*b[1] + a[2]*b[3], a[1]*b[2] + a[2]*b[4], | |
a[3]*b[1] + a[4]*b[3], a[3]*b[2] + a[4]*b[4], | |
} | |
end | |
local function matpow(m,p) | |
local r = { | |
m[1], m[2], | |
m[3], m[4], | |
} | |
for _ = 1, p do | |
r = matmul(r, m) | |
end | |
return r | |
end | |
local function fib(n) | |
return matpow({1,1,1,0}, n)[2] | |
end | |
return fib |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment