Skip to content

Instantly share code, notes, and snippets.

@cossio
Created July 23, 2018 14:14
Show Gist options
  • Save cossio/b3fc34822b2f2f0e9eb114cb3776b090 to your computer and use it in GitHub Desktop.
Save cossio/b3fc34822b2f2f0e9eb114cb3776b090 to your computer and use it in GitHub Desktop.
Fast doubling algorithm to compute Fibonacci numbers. This is faster than matrix exponentiation.
function fib(n::Integer)
@assert n ≥ 0
if iszero(n)
return zero(n)
elseif n == 1 || n == 2
return one(n)
end
k = div(n,2)
if iseven(n)
return fib(k) * (2fib(k+1) - fib(k))
else
return fib(k+1)^2 + fib(k)^2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment