Created
January 31, 2014 01:33
-
-
Save dbfin/8725049 to your computer and use it in GitHub Desktop.
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
-- Power modulo a number | |
powmod :: Int -> Int -> Int -> Int | |
powmod a pw n | pw <= 0 = 1 | |
| pw == 1 = a `mod` n | |
| even pw = powmod' (sqmod a n) (pw `div` 2) n 1 | |
| otherwise = powmod' (sqmod a n) (pw `div` 2) n (a `mod` n) | |
where | |
sqmod :: Int -> Int -> Int | |
sqmod a n = (a*a) `mod` n | |
powmod' :: Int -> Int -> Int -> Int -> Int | |
powmod' a pw n res | pw == 1 = (res * a) `mod` n | |
| even pw = powmod' (sqmod a n) (pw `div` 2) n res | |
| otherwise = powmod' (sqmod a n) (pw `div` 2) n ((res * a) `mod` n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment