Basically I used the classic divide and conquer whenever the exponent is even and came up with this.
int mymod(int a,int b){ //returns only positive value between 0 to b-1
return a%b<0 ? (a%b)+b : a%b;
}
int Solution::pow(int x, int n, int d) {
if(n==0) return mymod(1,d);
int result = 1;
while(n>0){
if(n%2 == 1)
result = mymod((result * x),d);
n = n>>1; //dividing exponent by 2, if it's even. Divide and conquer whenever exponent is even
x = mymod(x*x,d);
}
return result;
}
Now I'm using mymod function to calculate modulus, 'cuz normal modulus gave me a -ve result which wasn't in accordance with the test cases. I need to implement it with integers. There's one major thing to note here. Overflow situation. some test cases have large enough x, which when multiplied might overflow. Here are some of the test cases this program should satisfy.
X : 0
N : 0
D : 1
expected output: 0
X : -1
N : 1
D : 20
expected output: 19
X : 71045970
N : 41535484
D : 64735492
expected output: 20805472
The above code satisfies the first two test cases (TRIVIAL) but fails at the last test case. Python is also accepted by the OJ, I'll be needing a bit of an explanation in case of python. THANK YOU!!