I have written a code in java to find nth root of m, where n and m both are integers. 1 <= n <= 30 , 1 <= m <= 10^9
If the root is not integer then I have to return -1.
My code works for the smaller values of m and n. But it fails for n=6, m=4096 . My code returns -1, whereas the correct answer is 4. I think it happens because of overflow in the isProdGreater() method. How can I prevent this overflow?
public int NthRoot(int n, int m)
{
// code here
int l = 1, h = m;
int mid;
while(l<h){
mid = l + (h-l)/2;
//long prod = pow(mid,n);
if(isProdGreater(mid, n, m)){
h = mid;
}else{
l = mid+1;
}
}
if(l*l == m) return l;
return -1;
}
boolean isProdGreater(int x, int n, int target){
long a = 1;
for(int i=0; i<n; i++){
if(a*x >= target) return true;
a = a*x;
}
return false;
}
The problem is your last checking
if(l*l == m) return l;
This is checking the square, not the nth power. You probably want
if(Math.pow(l,n) == m) return l;