Created
October 2, 2013 03:00
-
-
Save trevordixon/6788535 to your computer and use it in GitHub Desktop.
Modular Exponentiation in Haskell
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.Bits | |
modExp :: Integer -> Integer -> Integer -> Integer | |
modExp b 0 m = 1 | |
modExp b e m = t * modExp ((b * b) `mod` m) (shiftR e 1) m `mod` m | |
where t = if testBit e 0 then b `mod` m else 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's a bold statement. And it's misguided. For many (if not most) inputs, @trevordixon's solution is much better.
Let's look at your example:
Yes, for this simple example, the simple approach works fine. But watch this:
Now the program will actually calculate
3^1000
, which has 478 decimal digits, and then it will take themod 23
of that huge number, which produces a two-digit number. Quite a waste of time and space. @trevordixon's solution never produces such huge intermediate results.