Created
April 17, 2019 16:56
-
-
Save amalloy/a6664c0f4187fcb946e44774cf95468c to your computer and use it in GitHub Desktop.
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 Data.Semigroup (stimes) | |
newtype Product = Product Integer | |
instance Semigroup Product where | |
Product x <> Product y = Product $ x * y | |
instance Monoid Product where | |
mempty = Product 1 | |
-- Implementing exponentiation by hand with N multiplications | |
-- *Main> let (Product x) = iterate (<> Product 2) (Product 2) !! 1000000 in x `mod` 10 | |
-- 2 (very slowly) | |
-- Letting Haskell do it in log(N) multiplications via repeated squaring | |
-- *Main> let (Product x) = stimes 10000001 (Product 2) in x `mod` 10 | |
-- 2 (very quickly) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment