TheAlgorithms/Java · error · IllegalArgumentException

Input numbers must be natural!

Error message

Input numbers must be natural!

What it means

Thrown by AmicableNumber.isAmicableNumber when either 'a' or 'b' is <= 0. The amicable relation is a property of positive integers (it relies on sumOfDividers), so any non-positive operand is rejected before computing divisor sums.

Source

Thrown at src/main/java/com/thealgorithms/maths/AmicableNumber.java:54

        Set<Pair<Integer, Integer>> result = new LinkedHashSet<>();

        for (int i = from; i < to; i++) {
            for (int j = i + 1; j <= to; j++) {
                if (isAmicableNumber(i, j)) {
                    result.add(Pair.of(i, j));
                }
            }
        }
        return result;
    }

    /**
     * Checks whether 2 numbers are AmicableNumbers or not.
     */
    public static boolean isAmicableNumber(int a, int b) {
        if (a <= 0 || b <= 0) {
            throw new IllegalArgumentException("Input numbers must be natural!");
        }
        return sumOfDividers(a, a) == b && sumOfDividers(b, b) == a;
    }

    /**
     * Recursively calculates the sum of all dividers for a given number excluding the divider itself.
     */
    private static int sumOfDividers(int number, int divisor) {
        if (divisor == 1) {
            return 0;
        } else if (number % --divisor == 0) {
            return sumOfDividers(number, divisor) + divisor;
        } else {
            return sumOfDividers(number, divisor);
        }
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass two positive integers: isAmicableNumber(220, 284).
  2. Guard both operands: if (a > 0 && b > 0) ... else handle.
  3. Start search loops at 1, not 0.

Example fix

// before
boolean am = AmicableNumber.isAmicableNumber(i, j);
// after
if (i <= 0 || j <= 0) continue;
boolean am = AmicableNumber.isAmicableNumber(i, j);
Defensive patterns

Strategy: validation

Validate before calling

if (a <= 0 || b <= 0) {
    throw new IllegalArgumentException("both numbers must be natural");
}
boolean am = AmicableNumber.isAmicableNumber(a, b);

Type guard

static boolean bothNatural(int a, int b) {
    return a > 0 && b > 0;
}

Try / catch

try {
    boolean am = AmicableNumber.isAmicableNumber(a, b);
} catch (IllegalArgumentException e) {
    // one or both operands were non-positive
}

Prevention

When it happens

Trigger: isAmicableNumber(0, 5); isAmicableNumber(220, -4); isAmicableNumber(0, 0); calling with a loop counter that started at 0.

Common situations: Looping i from 0 instead of 1; default-initialized int fields (0) passed before assignment; negative results from subtraction used as amicable candidates.

Related errors


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