Java Pow Of 2 Gives me a Wrong answer

66 Views Asked by At
class Solution {
    int mod = (int) (1e9) + 7;

    int modPow(long base, long exponent) {
        if (exponent == 0) return 1;

        long result = 1;
        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exponent /= 2;
        }
        return (int) result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int result = solution.modPow(2, (long) 1e9);
        System.out.println(result); // Output: 336781474
    }
}

Could you please find the error:
I got the wrong answer as: 140625001
but the correct output is: 336781474

1

There are 1 best solutions below

0
Archimedes Trajano On

Likely a precision error, try to use long rather than int and if that still does not give you the right answer use BigInteger which is an arbitrary precision number.