TheAlgorithms/Java · error · IllegalArgumentException

Input must me positive.

Error message

Input must me positive.

What it means

Thrown by DudeneyNumber.isDudeney when n <= 0. A Dudeney number equals the cube of the sum of its digits (e.g. 512 = (5+1+2)^3 = 8^3). The implementation computes an integer cube root and a digit sum, both of which require a positive integer; zero and negatives are outside the domain. Note the message itself contains a typo ('must me positive') but the check is correct.

Source

Thrown at src/main/java/com/thealgorithms/maths/DudeneyNumber.java:16

package com.thealgorithms.maths;

/**
 * A number is said to be Dudeney if the sum of the digits, is the cube root of the entered number.
 * Example- Let the number be 512, its sum of digits is 5+1+2=8. The cube root of 512 is also 8.
 *          Since, the sum of the digits is equal to the cube root of the entered number;
 *          it is a Dudeney Number.
 */
public final class DudeneyNumber {
    private DudeneyNumber() {
    }

    // returns True if the number is a Dudeney number and False if it is not a Dudeney number.
    public static boolean isDudeney(final int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("Input must me positive.");
        }
        // Calculating Cube Root
        final int cubeRoot = (int) Math.round(Math.pow(n, 1.0 / 3.0));
        // If the number is not a perfect cube the method returns false.
        if (cubeRoot * cubeRoot * cubeRoot != n) {
            return false;
        }

        // If the cube root of the number is not equal to the sum of its digits, we return false.
        return cubeRoot == SumOfDigits.sumOfDigits(n);
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a positive integer (>= 1) such as isDudeney(512).
  2. Validate at the caller boundary before invoking.
  3. If scanning a range, start the loop at 1, not 0.

Example fix

// before
boolean d = DudeneyNumber.isDudeney(0);

// after
boolean d = DudeneyNumber.isDudeney(512);
Defensive patterns

Strategy: validation

Validate before calling

if (n <= 0) {
    throw new IllegalArgumentException("Dudeney input must be > 0");
}
DudeneyNumber.isDudeney(n);

Type guard

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

Prevention

When it happens

Trigger: Calling isDudeney(0), isDudeney(-512), or passing an unvalidated value. The guard fires before Math.pow(n, 1.0/3.0) is evaluated.

Common situations: Unvalidated user input parsing to 0 or negative; a loop starting at 0; reusing a variable that was reset to a default of 0.

Related errors


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