I have two numbers A and B
where A and B can be in the range 1<= A,B <=100^100000
How can we find the value of A^B modulo some M in C++ ??
I have two numbers A and B
where A and B can be in the range 1<= A,B <=100^100000
How can we find the value of A^B modulo some M in C++ ??
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;
}