I was solving Nth root of M problem and I solved it with Java and here is the solution:
public int NthRoot(int n, int m)
{
// code here
int ans = -1;
if (m == 0)
return ans;
if (n == 1 || n == 0)
return m;
if (m == 1)
return 1;
int low = 1;
int high = m;
while (low < high) {
int mid = (low + high) / 2;
int pow = (int)Math.pow(mid, n);
if (pow == m) {
ans = mid;
break;
}
if (pow > m) {
high = mid;
} else {
low = mid + 1;
}
}
return ans;
}
It passed all the test cases. But, when I solved it using C++, some test cases didn't pass. Here is the C++ solution:
int NthRoot(int n, int m)
{
// Code here.
int ans = -1;
if (m == 0)
return ans;
if (n == 1 || n == 0)
return m;
if (m == 1)
return 1;
int low = 1;
int high = m;
while (low < high) {
int mid = (low + high) / 2;
int po = (int)pow(mid, n);
if (po == m) {
ans = (int)mid;
break;
}
if (po > m) {
high = mid;
} else {
low = mid + 1;
}
}
return ans;
}
One of the test cases it didn't pass is:
6 4096
Java's output is 4 (Expected result)
C++'s output is -1 (Incorrect result)
When I traced it using paper and pen, I got a solution the same as Java's.
But, when I used long long int
in the C++ code, it worked fine – but the size of Int
/int
in both Java and C++ are the same, right? (When I print INT_MAX
and Integer.MAX_VALUE
in C++ and Java, it outputs the same value.)