Skip to content

Instantly share code, notes, and snippets.

@dbfin
Created January 31, 2014 01:33
Show Gist options
  • Save dbfin/8725049 to your computer and use it in GitHub Desktop.
Save dbfin/8725049 to your computer and use it in GitHub Desktop.
-- 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