Modular exponentiation fails for large mod in C++

后端 未结 4 1072
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:34

    It seems that you can't avoid it.

    If mod is 10000000000ULL, in (a*b)%c in your program, both a and b are smaller than mod so we treat them as 9999999999ULL, a*b will be 99999999980000000001, but unsigned long long can only express 2^64-1=18446744073709551615 < 99999999980000000001 so your method will be overflow.

提交回复
热议问题