Modular exponentiation fails for large mod in C++

后端 未结 4 1069
Happy的楠姐
Happy的楠姐 2021-02-06 16:05

This is the code I\'m using for calculating (n^p)%mod. Unfortunately, it fails for large values of mod (in my case mod = 10000000000ULL) w

4条回答
  •  攒了一身酷
    2021-02-06 16:56

    One of the possible issues here seems to be that when you do (a*b)%c, the a*b part itself could overflow, resulting in a wrong answer. One way to work around that is to use the identity that

    (a*b)%c 
    

    is equivalent to

    (a%c * b%c)%c
    

    This will prevent overflows in the intermediate multiplications as well.

提交回复
热议问题