TheAlgorithms/Java · error · IllegalArgumentException
Must be a natural number
Error message
Must be a natural number
What it means
Thrown by CollatzConjecture.collatzConjecture when firstNumber < 1. The Collatz sequence is defined only over the natural numbers (positive integers): the rule halves even numbers and applies 3n+1 to odd numbers, terminating at 1. Zero and negative integers have no well-defined Collatz sequence, so the library rejects them before seeding the result list and the while loop.
Source
Thrown at src/main/java/com/thealgorithms/maths/CollatzConjecture.java:32
* @param n current number of the sequence
* @return next number of the sequence
*/
public int nextNumber(final int n) {
if (n % 2 == 0) {
return n / 2;
}
return 3 * n + 1;
}
/**
* Calculate the Collatz sequence of any natural number.
*
* @param firstNumber starting number of the sequence
* @return sequence of the Collatz Conjecture
*/
public List<Integer> collatzConjecture(int firstNumber) {
if (firstNumber < 1) {
throw new IllegalArgumentException("Must be a natural number");
}
ArrayList<Integer> result = new ArrayList<>();
result.add(firstNumber);
while (firstNumber != 1) {
result.add(nextNumber(firstNumber));
firstNumber = nextNumber(firstNumber);
}
return result;
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Pass a positive integer (>= 1) such as collatzConjecture(27).
- Validate the input at the caller boundary: if (firstNumber < 1) reject with a user-facing message.
- If parsing from a string, parse then range-check before invoking.
Example fix
// before List<Integer> seq = cc.collatzConjecture(0); // after List<Integer> seq = cc.collatzConjecture(1);
Defensive patterns
Strategy: validation
Validate before calling
if (firstNumber < 1) {
// reject with user-facing message
throw new IllegalArgumentException("Collatz start must be >= 1");
}
cc.collatzConjecture(firstNumber); Type guard
static boolean isNatural(int n) { return n >= 1; } Prevention
- Range-check all integer inputs parsed from strings or files before calling.
- Start scan loops at 1, not 0, when feeding Collatz.
- Validate at the application boundary, not deep inside processing.
When it happens
Trigger: Calling collatzConjecture(0), collatzConjecture(-5), or passing a value parsed from input that was not bounds-checked. The check fires before any sequence generation, so it triggers on the very first call with a non-natural number.
Common situations: User-supplied or file-parsed integer not validated; off-by-one in a loop that starts at 0 and feeds the method; testing with edge cases without realising the domain is strictly positive.
Related errors
- Input must be a positive integer.
- Input must me positive.
- n must be positive.
- number is negative
- n must be positive and odd.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/0dd593b8f540de0f.
Report an issue: GitHub.