TheAlgorithms/Java · error · IllegalArgumentException

additivePersistence() does not accept negative values

Error message

additivePersistence() does not accept negative values

What it means

Thrown by NumberPersistence.additivePersistence when num is negative. Additive persistence repeatedly sums the decimal digits of a number until a single digit remains; the digit-summing loop assumes a non-negative input. The guard rejects negatives before the loop starts.

Source

Thrown at src/main/java/com/thealgorithms/maths/NumberPersistence.java:63

            num = product;
            steps++;
        }
        return steps;
    }

    /**
     * Calculates the additive persistence of a given number.
     *
     * <p>Additive persistence is the number of steps required to reduce a number to a single digit
     * by summing its digits repeatedly.
     *
     * @param num the number to calculate persistence for; must be non-negative
     * @return the additive persistence of the number
     * @throws IllegalArgumentException if the input number is negative
     */
    public static int additivePersistence(int num) {
        if (num < 0) {
            throw new IllegalArgumentException("additivePersistence() does not accept negative values");
        }

        int steps = 0;
        while (num >= 10) {
            int sum = 0;
            int temp = num;
            while (temp > 0) {
                sum += temp % 10;
                temp /= 10;
            }
            num = sum;
            steps++;
        }
        return steps;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass Math.abs(num) when the magnitude is what matters.
  2. Validate num >= 0 at the input boundary and surface a domain error otherwise.
  3. Adjust upstream computation so non-negative values only reach this call.

Example fix

// before
int p = NumberPersistence.additivePersistence(value);

// after
int p = NumberPersistence.additivePersistence(Math.abs(value));
Defensive patterns

Strategy: validation

Validate before calling

int input = Math.abs(num);
int p = NumberPersistence.additivePersistence(input);

Prevention

When it happens

Trigger: Calling additivePersistence(-1) or any additivePersistence(num) where num < 0.

Common situations: Parsed integer from input where the sign was not validated; result of a subtraction passed in directly; numeric field deserialized from JSON without a min-constraint.

Related errors


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