简体   繁体   中英

Can someone explain this Integer modular behavior to me in Haskell?

*Test> ((3^40) `mod` 3) :: Int
2
*Test> ((3^40) `mod` 3)
0

Why is this so? I am using GHCi 7.0.3. If this is not a bug, an explanation of how Integral/Int works in haskell is appreciated, or a link to an explaination.

Thanks.

You're simply out of range, 3^40 is too big of a number to even fit in a 64-bit int:

Prelude> 3^40 :: Int
-6289078614652622815
Prelude> 3^40 :: Integer
12157665459056928801

The Integer type on the other hand is unbounded and accepts all numbers no matter how big. In your second case (where you got a 0 result) you got a type Integer inferred.

If you on using exponentiation only in the context of modular arithmetic, have a look at the powerMod function in the arithmoi package:

http://hackage.haskell.org/package/arithmoi

import Math.NumberTheory.Powers (powerMod)

test = powerMod 3 40 3

powerMod reduces the result while computing the exponentiation which should result in less work being done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM