Last active
January 17, 2017 00:43
-
-
Save robot-dreams/0069dd7558f898028659d41be9689185 to your computer and use it in GitHub Desktop.
Fibonacci in logarithmic time
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
fib :: Int -> Integer | |
fib n = | |
let fibTriplet k | |
| k <= 0 = (0, 0, 1) | |
| k == 1 = (0, 1, 1) | |
| even k = let (a, b, c) = fibTriplet (k `div` 2) | |
in (a^2 + b^2, b * (a + c), b^2 + c^2) | |
| odd k = let (a, b, c) = fibTriplet (k - 1) | |
in (b, c, b + c) | |
snd3 (_, y, _) = y | |
in snd3 $ fibTriplet n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment