Last active
August 14, 2021 01:27
-
-
Save friedbrice/37df508994d1e07243ca75bb6d79c912 to your computer and use it in GitHub Desktop.
Constant-memory, log-time fibonacci numbers.
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
import Data.Semigroup | |
data Fib = | |
Fib Integer Integer Integer | |
instance Semigroup Fib where | |
Fib a1 b1 c1 <> Fib a2 b2 c2 = | |
Fib (a1*a2 + b1*b2) (a1*b2 + b1*c2) (b1*b2 + c1*c2) | |
stimes = | |
mtimesDefault | |
instance Monoid Fib where | |
mempty = | |
Fib 1 0 1 | |
fibonacci n = | |
let | |
Fib _ y _ = stimes n (Fib 1 1 0) | |
in | |
y | |
main = | |
print . fibonacci . read =<< getContents |
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
daniel@newport:~/Desktop | |
$ ghc -O2 fibonacci.hs | |
[1 of 1] Compiling Main ( fibonacci.hs, fibonacci.o ) | |
Linking fibonacci ... | |
daniel@newport:~/Desktop | |
$ echo 1000000000 | time ./fibonacci > fib-1000000000.txt | |
88.41 real 85.37 user 2.52 sys | |
daniel@newport:~/Desktop | |
$ ls -l fib-1000000000.txt | |
-rw-r--r-- 1 daniel staff 200M Aug 13 18:25 fib-1000000000.txt | |
daniel@newport:~/Desktop | |
$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
RE: https://www.reddit.com/r/math/comments/p3rgp9/ever_wondered_what_the_100000th_fibonacci_number/