TheAlgorithms/Java · error · IllegalArgumentException

numOfTerms nonnegative.

Error message

numOfTerms nonnegative.

What it means

Thrown by SumOfArithmeticSeries.sumOfSeries when numOfTerms is negative. The closed-form formula (n/2 * (2a + (n-1)d)) is mathematically defined for non-negative term counts; a negative count has no meaning as 'number of terms'. The message text ('numOfTerms nonnegative.') is a terse fragment rather than a full sentence.

Source

Thrown at src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java:27

 *
 * <p>
 * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression
 */
public final class SumOfArithmeticSeries {
    private SumOfArithmeticSeries() {
    }

    /**
     * Calculate sum of arithmetic series
     *
     * @param firstTerm the initial term of an arithmetic series
     * @param commonDiff the common difference of an arithmetic series
     * @param numOfTerms the total terms of an arithmetic series
     * @return sum of given arithmetic series
     */
    public static double sumOfSeries(final double firstTerm, final double commonDiff, final int numOfTerms) {
        if (numOfTerms < 0) {
            throw new IllegalArgumentException("numOfTerms nonnegative.");
        }
        return (numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff));
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure numOfTerms >= 0 before calling; treat 0 terms as sum 0 if that matches your domain.
  2. Fix the upstream computation producing the negative count.
  3. Consider contributing a clearer message upstream ('numOfTerms must be non-negative').

Example fix

// before
double s = SumOfArithmeticSeries.sumOfSeries(a, d, terms);

// after
if (terms < 0) throw new IllegalArgumentException("terms must be >= 0, got " + terms);
double s = SumOfArithmeticSeries.sumOfSeries(a, d, terms);
Defensive patterns

Strategy: validation

Validate before calling

if (numOfTerms < 0) throw new IllegalArgumentException("numOfTerms must be >= 0");
double s = SumOfArithmeticSeries.sumOfSeries(a, d, numOfTerms);

Prevention

When it happens

Trigger: Call sumOfSeries(firstTerm, commonDiff, -1) or pass a term count derived from a subtraction/collection size that went negative.

Common situations: Miscomputing a length (e.g., end - start with start > end), off-by-one on a parsed count, or assuming a size method never returns negative.

Related errors


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