Modular exponentiation fails for large mod in C++

后端 未结 4 1078
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条回答
  •  -上瘾入骨i
    2021-02-06 16:48

    Your code line

     n = (n*n)%mod;
    

    is repeatedly executed. As long as n is smaller than mod, this will potentially result in evaluating (mod-1)*(mod-1) at some point in time.

    On input n may not be so large, but the mentioned line of code increases n in the loop.

提交回复
热议问题