Computing the Nth power of a number

suggest change

The following method computes the value of num raised to the power of exp using recursion:

public long power(final int num, final int exp) {
    if (exp == 0) {
        return 1;
    }
    if (exp == 1) {
        return num;
    }
    return num * power(num, exp - 1);
}

The method implements a base case (two cases, exp == 0 and exp == 1) that terminates the recursion, and a recursive case that calls the method again. It is O(exp) and can be rewritten as a loop. The JVM does not apply tail-call optimization, so this version still uses O(exp) stack frames. A negative exp never hits the base case and recurses until the stack overflows. The long result also overflows silently when the power does not fit.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents