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
- Validate n >= 0 at the caller and reject or clamp before calling perrin.
- Fix the upstream arithmetic (loop bounds, subtractions) producing the negative index.
- 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
- Validate sequence indices for non-negativity before calling.
- Audit index arithmetic (subtractions, loop bounds) for negative results.
- Reject negative indices at the API boundary with a domain-specific error.
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
- n must be non-negative.
- Input must be non-negative. Received:
- baseNumbers must be non-empty.
- Input must be non-negative!
- Input x-coordinates must be unique.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/0459ce45264d08ab.
Report an issue: GitHub.