TheAlgorithms/Java · error · IllegalArgumentException

Input must be non-negative. Received:

Error message

Input must be non-negative. Received: 

What it means

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

Source

Thrown at src/main/java/com/thealgorithms/maths/PadovanSequence.java:26

 * @see <a href="https://en.wikipedia.org/wiki/Padovan_sequence">
 *     Wikipedia: Padovan Sequence</a>
 * @author Vraj Prajapati (@Rosander0)
 */
public final class PadovanSequence {

    private PadovanSequence() {
        // Utility class
    }

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

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate n >= 0 at the caller and reject/clamp before invoking padovan.
  2. Fix the upstream arithmetic (loop bounds, subtractions) producing the negative index.
  3. If your domain allows negative indices, define your own extension and remap before calling.

Example fix

// before
long v = PadovanSequence.padovan(idx);

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

Strategy: validation

Validate before calling

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

Prevention

When it happens

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

Common situations: Index computed from an expression like (n - k) that can go negative; user-supplied sequence index not sanitized; off-by-one in a loop that should exclude 0; deserialized query parameter that accepted negative values.

Related errors


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