TheAlgorithms/Java · error · IllegalArgumentException

Input must be non-negative!

Error message

Input must be non-negative!

What it means

Thrown by PerrinNumber.perrin(int n) when n is negative. The Perrin sequence is defined for non-negative indices (P(0)=3, P(1)=0, P(2)=2, P(n)=P(n-2)+P(n-3)); a negative index has no defined value and would break the iterative loop. The guard fires before the base-case checks.

Source

Thrown at src/main/java/com/thealgorithms/maths/PerrinNumber.java:30

 * @see <a href="https://en.wikipedia.org/wiki/Perrin_number">
 *     Wikipedia: Perrin Number</a>
 * @see PadovanSequence
 */
public final class PerrinNumber {

    private PerrinNumber() {
        // Utility class
    }

    /**
     * Calculates the nth term of the Perrin Sequence.
     *
     * @param n the index of the sequence (must be non-negative)
     * @return the nth term of the Perrin Sequence
     */
    public static long perrin(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input must be non-negative!");
        }
        if (n == 0) {
            return 3;
        }
        if (n == 1) {
            return 0;
        }
        if (n == 2) {
            return 2;
        }
        long a = 3;
        long b = 0;
        long c = 2;
        long result = 0;
        for (int i = 3; i <= n; i++) {
            result = a + b;
            a = b;
            b = c;

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate n >= 0 at the caller and reject or clamp before calling perrin.
  2. Fix the upstream arithmetic (loop bounds, subtractions) producing the negative index.
  3. If negative indices are meaningful in your domain, define your own mapping before calling.

Example fix

// before
long v = PerrinNumber.perrin(idx);

// after
if (idx < 0) {
    throw new IllegalArgumentException("idx must be >= 0: " + idx);
}
long v = PerrinNumber.perrin(idx);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("n must be >= 0: " + n);
}
long v = PerrinNumber.perrin(n);

Prevention

When it happens

Trigger: Calling perrin(-1) or any perrin(n) where n < 0.

Common situations: Index computed from an arithmetic expression that can go negative; user-supplied index not validated; off-by-one in a loop bound; deserialized parameter that accepted negative integers.

Related errors


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