Modular Exponentiation for high numbers in C++

前端 未结 6 1741
失恋的感觉
失恋的感觉 2020-12-01 12:48

So I\'ve been working recently on an implementation of the Miller-Rabin primality test. I am limiting it to a scope of all 32-bit numbers, because this is a just-for-fun pr

6条回答
  •  旧时难觅i
    2020-12-01 13:32

    Two things:

    • Are you using the appropriate data type? In other words, does UINT_MAX allow you to have 673109 as an argument?

    No, it does not, since at one point you have Your code does not work because at one point you have num = 2^16 and the num = ... causes overflow. Use a bigger data type to hold this intermediate value.

    • How about taking modulo at every possible overflow oppertunity such as:

      test = ((test % mod) * (num % mod)) % mod;

    Edit:

    unsigned mod_pow(unsigned num, unsigned pow, unsigned mod)
    {
        unsigned long long test;
        unsigned long long n = num;
        for(test = 1; pow; pow >>= 1)
        {
            if (pow & 1)
                test = ((test % mod) * (n % mod)) % mod;
            n = ((n % mod) * (n % mod)) % mod;
        }
    
        return test; /* note this is potentially lossy */
    }
    
    int main(int argc, char* argv[])
    {
    
        /* (2 ^ 168277) % 673109 */
        printf("%u\n", mod_pow(2, 168277, 673109));
        return 0;
    }
    

提交回复
热议问题