Created
July 23, 2018 14:14
-
-
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.
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
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