TheAlgorithms/Java · error · IllegalArgumentException

Exponent must be non-negative.

Error message

Exponent must be non-negative.

What it means

Thrown by Pow.pow(int a, int b) when the exponent b is negative. This implementation computes a^b by iterative multiplication (b times), which cannot represent a negative exponent (which would yield a fractional result). The guard rejects negatives before the loop to avoid an incorrect result of 1.

Source

Thrown at src/main/java/com/thealgorithms/maths/Pow.java:28

public final class Pow {
    private Pow() {
    }

    /**
     * Computes the value of the base raised to the power of the exponent.
     * <p>
     * The method calculates {@code a}<sup>{@code b}</sup> by iteratively multiplying the base {@code a} with itself {@code b} times.
     * If the exponent {@code b} is negative, an {@code IllegalArgumentException} is thrown.
     * </p>
     *
     * @param a the base of the exponentiation. Must be a non-negative integer.
     * @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer.
     * @return the result of {@code a}<sup>{@code b}</sup> as a {@code long}.
     * @throws IllegalArgumentException if {@code b} is negative.
     */
    public static long pow(int a, int b) {
        if (b < 0) {
            throw new IllegalArgumentException("Exponent must be non-negative.");
        }
        long result = 1;
        for (int i = 1; i <= b; i++) {
            result *= a;
        }
        return result;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. If you need negative exponents, use Math.pow(a, b) (returns double) or implement a reciprocal variant.
  2. Validate b >= 0 at the caller and reject or clamp before calling pow.
  3. Fix upstream arithmetic so only non-negative exponents reach this call.

Example fix

// before
long r = Pow.pow(base, exp);

// after
long r = exp < 0 ? (long) Math.pow(base, exp) : Pow.pow(base, exp);
Defensive patterns

Strategy: validation

Validate before calling

if (b < 0) {
    // use double-precision power for negative exponents
    double r = Math.pow(a, b);
} else {
    long r = Pow.pow(a, b);
}

Prevention

When it happens

Trigger: Calling pow(a, -1) or any pow(a, b) where b < 0.

Common situations: Exponent computed from user input or a subtraction that can go negative; assumption that pow handles reciprocals; passing a loop counter that underflows; misreading the contract and expecting Math.pow semantics.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/190b7fcce83f5578. Report an issue: GitHub.