How can I calculate the power of an integer in Java without using doubles?

I’m currently using Math.pow(a, b) to calculate powers in Java, but it returns a double, which makes my code less clean when I only need integer results.

Is there a simple way to compute the power of 2 in Java (or any integer power) without dealing with floating-point values? Something as straightforward as a**b in Python?

If you want to compute integer powers without using Math.pow(), the simplest way is to use a loop:

public static int power(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    return result;
}

Things to note:

  • :white_check_mark: Works for non-negative exponents
  • :x: Not efficient for large exponents

That’s a good approach, but recursion can make the code cleaner. Here’s a recursive method:

public static int power(int base, int exponent) {
    if (exponent == 0) return 1;
    return base * power(base, exponent - 1);
}
  • More readable
  • Can cause stack overflow for large exponent

Both methods above work, but for large numbers, an optimized approach is Exponentiation by Squaring (used in competitive programming & cryptography).

public static int power(int base, int exponent) {
    if (exponent == 0) return 1;
    int halfPower = power(base, exponent / 2);
    if (exponent % 2 == 0) {
        return halfPower * halfPower;
    } else {
        return base * halfPower * halfPower;
    }
}
  • O(log n) complexity (much faster than O(n))
  • Best for large exponent values