C/C++ Large number calculation

半腔热情 提交于 2019-12-04 10:44:17

The simplest method is exponentiation by repeated squaring reducing by the modulus in each step.

unsigned long long mod_pow(unsigned long long base, unsigned long long exponent, unsigned long long modulus)
{
    if (exponent == 0) return 1;
    unsigned long long aux = 1;
    while(exponent > 1) {
        if (exponent % 2 != 0) {
            aux *= base;
            aux %= modulus;
        }
        base *= base;
        base %= modulus;
        exponent /= 2;
    }
    return (base*aux) % modulus;
}

You can then use that to compute

result = (3*mod_pow(2,500000000,1000000000) - 2) % 1000000000;

The function supposes that the square of the modulus does not exceed the 64-bit range. For larger moduli, things are more complicated.

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