Skip to content

Instantly share code, notes, and snippets.

@cjtallman
Created December 19, 2017 21:33
Show Gist options
  • Save cjtallman/b425505709e8012946e2d0d769dd29ac to your computer and use it in GitHub Desktop.
Save cjtallman/b425505709e8012946e2d0d769dd29ac to your computer and use it in GitHub Desktop.
Fast Fibonacci
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