TheAlgorithms/Java · error · IllegalArgumentException

multiplicativePersistence() does not accept negative values

Error message

multiplicativePersistence() does not accept negative values

What it means

Thrown by NumberPersistence.multiplicativePersistence when num is negative. Persistence is defined for non-negative integers (it repeatedly multiplies decimal digits), and the digit-extraction loop relies on num being non-negative. The guard rejects negatives before entering the loop.

Source

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

public final class NumberPersistence {

    // Private constructor to prevent instantiation
    private NumberPersistence() {
    }

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

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

    /**
     * Calculates the additive persistence of a given number.

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass Math.abs(num) if the persistence of the magnitude is acceptable for your use case.
  2. Validate input >= 0 at the boundary (form/parser) and reject negatives with a domain-specific error.
  3. Fix upstream logic so only non-negative values reach this call.

Example fix

// before
int p = NumberPersistence.multiplicativePersistence(delta);

// after
int p = NumberPersistence.multiplicativePersistence(Math.abs(delta));
Defensive patterns

Strategy: validation

Validate before calling

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

Prevention

When it happens

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

Common situations: Caller passes user input or parsed text without sign normalization; absolute-value transformation missing in a pipeline that processes differences (which can be negative); a subtraction result fed directly into the method.

Related errors


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