To Find Large Powers in C++ [duplicate]

蓝咒 提交于 2019-12-03 21:29:40
Floris

In the duplicate I pointed out, the solution I particularly like is https://stackoverflow.com/a/8972838/1967396 (see there for attribution and references)

For your convenience I reproduce the code here (wrapped into an SCCE - but using C, not C++):

#include <stdio.h>

int modular(int base, unsigned int exp, unsigned int mod)
{
    int x = 1;
    int i;
    int power = base % mod;

    for (i = 0; i < sizeof(int) * 8; i++) {
        int least_sig_bit = 0x00000001 & (exp >> i);
        if (least_sig_bit)
            x = (x * power) % mod;
        power = (power * power) % mod;
    }

    return x;
}

int main(void) {
  printf("123^456mod567 = %d\n", modular(123, 456, 567));
}

Amazing, isn't it.

use the formula (a*b)mod m = (a*(b (mod m))) (mod m). For more details see the wiki page Modular exponentiation

Another solution assumes that your M is fixed (or at least that you need to compute A^B many times with the same M).

Step 1: compute the Euler's totient function (this requires a factorization of M, so it's quite expensive). Let's call this number k.

Due to the Fermat's little theorem, your answer is simply:

(a % M)^(b % k)

Now, unless M is a large prime number, this greatly simplify the problem.

The above problem can be solved using the code snippet below. Thus to ensure this code does not overflow, check that n * n <= 2 ^ 31.

int modPow(int base, int exp, int n) {

base = base%n;

if (exp == 0)
    return 1;

else if (exp == 1)
    return base;

else if (exp%2 == 0)
    return modPow(base*base%n, exp/2, n);

else
    return base*modPow(base, exp-1, n)%n; 

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!