TheAlgorithms/Java · error · IllegalArgumentException

n must be positive.

Error message

n must be positive.

What it means

Thrown by EulersFunction.checkInput (invoked by getEuler) when n <= 0. Euler's totient function phi(n) counts integers up to n coprime to n and is defined for positive integers only. The private checkInput helper centralises this precondition so getEuler can assume n >= 1 in its O(sqrt(n)) factorisation loop.

Source

Thrown at src/main/java/com/thealgorithms/maths/EulersFunction.java:19

package com.thealgorithms.maths;

/**
 * Utility class for computing
 * <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function">Euler's totient function</a>.
 */
public final class EulersFunction {
    private EulersFunction() {
    }

    /**
     * Validates that the input is a positive integer.
     *
     * @param n the input number to validate
     * @throws IllegalArgumentException if {@code n} is non-positive
     */
    private static void checkInput(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n must be positive.");
        }
    }

    /**
     * Computes the value of Euler's totient function for a given input.
     * This function has a time complexity of O(sqrt(n)).
     *
     * @param n the input number
     * @return the value of Euler's totient function for the given input
     * @throws IllegalArgumentException if {@code n} is non-positive
     */
    public static int getEuler(int n) {
        checkInput(n);
        int result = n;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                while (n % i == 0) {
                    n /= i;

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a positive integer (>= 1) such as getEuler(36).
  2. Validate at the caller: if (n <= 0) reject before calling.
  3. Clamp derived values with Math.max(1, n).

Example fix

// before
int phi = EulersFunction.getEuler(0);

// after
int phi = EulersFunction.getEuler(36);
Defensive patterns

Strategy: validation

Validate before calling

if (n <= 0) {
    throw new IllegalArgumentException("Euler totient requires n >= 1");
}
EulersFunction.getEuler(n);

Type guard

static boolean isPositive(int n) { return n > 0; }

Prevention

When it happens

Trigger: Calling getEuler(0), getEuler(-10), or passing an unvalidated integer. The check runs before the totient computation begins.

Common situations: User input parsed to 0 or negative; loop starting at 0; default int value of 0 passed inadvertently; n derived from a subtraction that underflowed.

Related errors


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