TheAlgorithms/Java · error · IllegalArgumentException

Number must be non-negative. Given:

Error message

Number must be non-negative. Given: 

What it means

Thrown by isKaprekarNumber(long num) when the input is negative. A Kaprekar number is one whose square can be split into left and right parts that sum back to the original (e.g., 45 squared is 2025, and 20+25=45). The method requires non-negative input because the algorithm splits the squared representation, and negative numbers have no meaningful split semantics.

Source

Thrown at src/main/java/com/thealgorithms/maths/KaprekarNumbers.java:81

     * <p>
     * The algorithm works as follows:
     * <ol>
     * <li>Square the number</li>
     * <li>Split the squared number into two parts: left and right</li>
     * <li>The right part has the same number of digits as the original number</li>
     * <li>Add the left and right parts</li>
     * <li>If the sum equals the original number, it's a Kaprekar number</li>
     * </ol>
     * <p>
     * Special handling is required for numbers whose squares contain zeros.
     *
     * @param num the number to check
     * @return true if the number is a Kaprekar number, false otherwise
     * @throws IllegalArgumentException if num is negative
     */
    public static boolean isKaprekarNumber(long num) {
        if (num < 0) {
            throw new IllegalArgumentException("Number must be non-negative. Given: " + num);
        }

        if (num == 0 || num == 1) {
            return true;
        }

        String number = Long.toString(num);
        BigInteger originalNumber = BigInteger.valueOf(num);
        BigInteger numberSquared = originalNumber.multiply(originalNumber);
        String squaredStr = numberSquared.toString();

        // Special case: if the squared number has the same length as the original
        if (number.length() == squaredStr.length()) {
            return number.equals(squaredStr);
        }

        // Calculate the split position
        int splitPos = squaredStr.length() - number.length();

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate that the input is >= 0 before calling isKaprekarNumber
  2. Filter or reject negative inputs at the data-ingestion boundary (API handler, file parser) rather than at the algorithm call site
  3. If the absolute value is acceptable for your use case, pass Math.abs(num) instead

Example fix

// before
boolean result = KaprekarNumbers.isKaprekarNumber(userInput);

// after
if (userInput < 0) {
    throw new IllegalArgumentException("Input must be non-negative: " + userInput);
}
boolean result = KaprekarNumbers.isKaprekarNumber(userInput);
Defensive patterns

Strategy: validation

Validate before calling

if (num < 0) {
    throw new IllegalArgumentException("Input must be non-negative: " + num);
}
boolean result = KaprekarNumbers.isKaprekarNumber(num);

Type guard

static boolean isValidKaprekarInput(long num) {
    return num >= 0;
}

Try / catch

try {
    boolean result = KaprekarNumbers.isKaprekarNumber(num);
} catch (IllegalArgumentException e) {
    // handle invalid input — log and skip or default to false
    logger.warn("Invalid Kaprekar input: {}", num);
}

Prevention

When it happens

Trigger: Calling KaprekarNumbers.isKaprekarNumber(-1) or passing any negative long value. Also triggered by downstream code that forwards unparsed user input or database sentinel values like -1.

Common situations: Accepting user input from a text field or API parameter that was not range-validated. Processing data files where missing values are encoded as -1. Subtracting two values where the result may go negative before passing to isKaprekarNumber.

Related errors


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