Created
March 25, 2018 00:52
-
-
Save Gabriella439/c6518cfaf3dc8b83def9148f4d6d8ea3 to your computer and use it in GitHub Desktop.
Efficient fibonacci numbers using infinite precision integer arithmetic
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
import Numeric.Natural (Natural) | |
import qualified Data.Semigroup | |
-- | @fibonacci n@ computes the @nth@ fibonacci number efficiently using infinite | |
-- precision integer arithmetic | |
-- | |
-- Try @fibonacci 1000000@ | |
fibonacci :: Natural -> Natural | |
fibonacci n = x01 (Data.Semigroup.mtimesDefault n m) | |
where | |
m = Matrix_2x2 | |
{ x00 = 0, x01 = 1 | |
, x10 = 1, x11 = 1 | |
} | |
data Matrix_2x2 = | |
Matrix_2x2 | |
{ x00 :: Natural, x01 :: Natural | |
, x10 :: Natural, x11 :: Natural | |
} | |
instance Monoid Matrix_2x2 where | |
mempty = | |
Matrix_2x2 | |
{ x00 = 1, x01 = 0 | |
, x10 = 0, x11 = 1 | |
} | |
mappend l r = | |
Matrix_2x2 | |
{ x00 = x00 l * x00 r + x01 l * x10 r, x01 = x00 l * x01 r + x01 l * x11 r | |
, x10 = x10 l * x00 r + x11 l * x10 r, x11 = x10 l * x01 r + x11 l * x11 r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment