Last active
June 14, 2018 14:32
-
-
Save kevin-lee/9192f7ea3ba6962f0d7fea275338b775 to your computer and use it in GitHub Desktop.
Examples of Fibonacci number function
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
fib 0 = 0 | |
fib 1 = 1 | |
fib 2 = 1 | |
fib n = fib (n - 1) + fib (n - 2) | |
-- Get the 100th number | |
fib 100 | |
-- But it takes too long. | |
-- You can do it with zipWith like the following line and it works much faster | |
fibs = 0 : 1 : 1 : zipWith (+) (drop 1 fibs) (drop 2 fibs) | |
-- Get the 100th number. Why 99? because the fist number is 0th element. | |
fibs !! 99 | |
-- 218922995834555169026 | |
-- This can fix that issue. | |
fibAt n = fibs !! (n - 1) where fibs = 0 : 1 : 1 : zipWith (+) (drop 1 fibs) (drop 2 fibs) | |
-- The 100th fibonacci number | |
fibAt 100 | |
-- 218922995834555169026 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment