Reputation: 19
How do I carry out the following modulo operation in java.
5^7 mod 11 = 5^(2+2+2+1) mod 11.
I tried using for loop, but I am not able to get the required output
Upvotes: 0
Views: 1664
Reputation: 109567
As this seems homework, I'll give the recursive version of what might be intended: using the exponent's binary decomposition:
x^(2n) = q * q where q = 2^n
int pow(int base, int exp, int modulo) {
if (exp == 0) {
return 1;
}
base %= modulo;
if (exp == 1) {
return base;
}
if (exp % 2 == 1) {
return (base * pow(base, exp, modulo)) % modulo;
}
int sqroot = pow(base, exp / 2, modulo) % modulo;
return (sqroot * sqroot) % modulo;
}
int result = pow(5, 7, 11);
As the modulo is a prime, as is the base, there are several optimizations possible.
Upvotes: 0
Reputation: 65821
Here's both ways:
public void testMath(int x, int y, int z) {
double pow = Math.pow(x, y);
double mod = pow % z;
System.out.println("Math - pow(" + x + "," + y + "," + z + ") = " + pow + " mod = " + mod);
}
public void testLoop(int x, int y, int z) {
double v = 1;
for (int i = 0; i < y; i++) {
v *= x;
v %= z;
}
System.out.println("Math - pow(" + x + "," + y + "," + z + ") = " + " mod = " + v);
}
public void test() {
testMath(5, 7, 11);
testLoop(5, 7, 11);
}
Upvotes: 0
Reputation: 7068
You don't need to use a loop for this operation. You can just use:
Math.pow(5.0,7.0) % 11.0
Upvotes: 1