int Solution::pow(int x, int n, int d) {
// If a is 0
if(x==0) return0;
long res=1;
while(n>0){
// If y is odd, multiply x to the result.
if(n&1) res = (res*x)%d;
n = n>>1; // reduce y by half
x = (x*x)%d; // Since we have reduce y by half,
// that's why we have to square x.
}
return (d + res)%d;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
publicintpow(int x, int n, int d) {
if (x == 0) {
return 0;
}
long a1 = x % d;
long p = 1;
while (n > 0) {
if ((n & 1) == 1) {
p = (p * a1) % d;
}
n /= 2;
a1 = (a1 * a1) % d;
}
if (p < 0) {
return (int) ((p + d) % d);
} else {
return (int) p;
}
}