C/C++ Large number calculation

2020-07-18 07:12发布

问题:

I'm trying to compute the following number in a C program :

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

The power of 2 is way to large to be handled properly => I'm under the impression I could split the calculation in many steps using the modulo to reduce the result size. Does someone has a strategy for doing so ? Any other idea ?

Thanx in advance

Manu

回答1:

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.