Different outputs for Java and CPP

  algorithm, ambiguous, binary-search, c++, java

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 of 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 the solution as same as Java’s.

But when I used long long int in C++’s code it worked fine.
But the size of Int in both Java and C++ are the same, right?

When I printed INT_MAX and Integer.MAX_VALUE in C++ and Java, it outputted the same value.

It will be really helpful, if anyone solves this ambiguity. Thanks!

Source: Windows Questions C++

LEAVE A COMMENT