TheAlgorithms/Java · error · IllegalArgumentException

Input must be non-negative

Error message

Input must be non-negative

What it means

Thrown by SumOfSquares.minSquares(int n) when n is negative. The method implements Lagrange's four-square theorem (every non-negative integer is a sum of <= 4 perfect squares), which is undefined for negatives; the guard prevents the algorithm from looping on invalid input.

Source

Thrown at src/main/java/com/thealgorithms/maths/SumOfSquares.java:24

 *
 * @see <a href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem">Lagrange's Four Square Theorem</a>
 */
public final class SumOfSquares {

    private SumOfSquares() {
        // Utility class
    }

    /**
     * Find minimum number of perfect squares that sum to n
     *
     * @param n the target number (must be non-negative)
     * @return minimum number of squares needed
     * @throws IllegalArgumentException if n is negative
     */
    public static int minSquares(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input must be non-negative");
        }

        if (isPerfectSquare(n)) {
            return 1;
        }

        for (int i = 1; i * i <= n; i++) {
            int remaining = n - i * i;
            if (isPerfectSquare(remaining)) {
                return 2;
            }
        }

        // Legendre's three-square theorem
        int temp = n;
        while (temp % 4 == 0) {
            temp /= 4;
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate n >= 0 before calling.
  2. Use Math.max(0, n) if negatives should be treated as 0.
  3. Surface the constraint to the user/API consumer explicitly.

Example fix

// before
int k = SumOfSquares.minSquares(n);

// after
if (n < 0) throw new IllegalArgumentException("n must be >= 0, got " + n);
int k = SumOfSquares.minSquares(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) throw new IllegalArgumentException("n must be >= 0");
int k = SumOfSquares.minSquares(n);

Prevention

When it happens

Trigger: Call minSquares(-1) or pass a target computed from a subtraction that went negative.

Common situations: Untested numeric input, an expression like (target - offset) with offset > target, or porting unsigned-arithmetic assumptions.

Related errors


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