TheAlgorithms/Java · error · IllegalArgumentException

Number must be greater than zero.

Error message

Number must be greater than zero.

What it means

Thrown by MobiusFunction.mobius(int number) when number <= 0. The Möbius function μ(n) is defined only for positive integers, so zero and negatives are out of domain. The guard fires before the special-case handling for n == 1 and the prime-factor loop.

Source

Thrown at src/main/java/com/thealgorithms/maths/Prime/MobiusFunction.java:31

 *
 * */
public final class MobiusFunction {
    private MobiusFunction() {
    }

    /**
     * This method returns μ(n) of given number n
     *
     * @param number Integer value which μ(n) is to be calculated
     * @return  1 when number is less than or equals 1
     *            or number has even number of prime factors
     *          0 when number has repeated prime factor
     *         -1 when number has odd number of prime factors
     */
    public static int mobius(int number) {
        if (number <= 0) {
            // throw exception when number is less than or is zero
            throw new IllegalArgumentException("Number must be greater than zero.");
        }

        if (number == 1) {
            // return 1 if number passed is less or is 1
            return 1;
        }

        int primeFactorCount = 0;

        for (int i = 1; i <= number; i++) {
            // find prime factors of number
            if (number % i == 0 && PrimeCheck.isPrime(i)) {
                // check if number is divisible by square of prime factor
                if (number % (i * i) == 0) {
                    // if number is divisible by square of prime factor
                    return 0;
                }
                /*increment primeFactorCount by 1

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate number > 0 at the caller and reject or clamp before calling mobius.
  2. Fix upstream arithmetic producing non-positive values.
  3. Define domain-specific handling for 0/negatives before invoking the function.

Example fix

// before
int mu = MobiusFunction.mobius(n);

// after
if (n <= 0) {
    throw new IllegalArgumentException("n must be > 0: " + n);
}
int mu = MobiusFunction.mobius(n);
Defensive patterns

Strategy: validation

Validate before calling

if (number <= 0) {
    throw new IllegalArgumentException("number must be > 0: " + number);
}
int mu = MobiusFunction.mobius(number);

Prevention

When it happens

Trigger: Calling mobius(0), mobius(-3), or any mobius(number) where number <= 0.

Common situations: User-supplied integer not validated for positivity; arithmetic expression (subtraction, decrement) crossing zero; loop bound off-by-one hitting 0; deserialized numeric field that accepted non-positive values.

Related errors


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