TheAlgorithms/Java · error · IllegalArgumentException
The exponent must be positive
Error message
The exponent must be positive
What it means
Thrown by ModuloPowerOfTwo.moduloPowerOfTwo(int x, int n) when n <= 0. The method computes x mod 2^n via the bit trick x & ((1 << n) - 1). For n = 0 the mask degenerates to 0 (always-yielding 0, not the intended modulo), and for n < 0 the shift is undefined for this trick, so the library requires a strictly positive exponent.
Source
Thrown at src/main/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwo.java:23
* of a number when divided by a power of two (2^n)
* without using division or modulo operations.
*
* @author Hardvan
*/
public final class ModuloPowerOfTwo {
private ModuloPowerOfTwo() {
}
/**
* Computes the remainder of a given integer when divided by 2^n.
*
* @param x the input number
* @param n the exponent (power of two)
* @return the remainder of x divided by 2^n
*/
public static int moduloPowerOfTwo(int x, int n) {
if (n <= 0) {
throw new IllegalArgumentException("The exponent must be positive");
}
return x & ((1 << n) - 1);
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Ensure the exponent is at least 1 before calling (n >= 1).
- Recompute the exponent source so it cannot reach 0 (e.g. require size >= 2).
- If you need modulo by 1 (result always 0), short-circuit that case explicitly before calling.
Example fix
// before int r = ModuloPowerOfTwo.moduloPowerOfTwo(x, log2(size)); // after int exp = Integer.numberOfTrailingZeros(size); int r = exp > 0 ? ModuloPowerOfTwo.moduloPowerOfTwo(x, exp) : 0;
Defensive patterns
Strategy: validation
Validate before calling
if (n <= 0) {
throw new IllegalArgumentException("exponent n must be >= 1");
}
int r = ModuloPowerOfTwo.moduloPowerOfTwo(x, n); Type guard
static boolean validExponent(int n) { return n >= 1; } Try / catch
try {
int r = ModuloPowerOfTwo.moduloPowerOfTwo(x, n);
} catch (IllegalArgumentException e) {
// n was <= 0; fall back to x mod 1 == 0 only if that is intended
} Prevention
- When deriving n from a power-of-two size, ensure the size is >= 2.
- Reject size == 1 upstream since its exponent is 0.
- Default exponent config to a safe positive value, never 0.
When it happens
Trigger: Calling moduloPowerOfTwo(x, n) with n == 0 or n < 0. Common when n is computed as log2 of a size and the size is 1 (giving 0) or when an uninitialized/default int (0) is passed.
Common situations: Deriving the exponent from an array/buffer size via bit-length where the size is a power of two equal to 1; config value left at default 0; off-by-one in computing power from a divisor.
Related errors
- Input cannot be negative
- Input must be a non-empty binary string.
- Input must contain only '0' and '1'. Found: {}
- Input must contain only '0' and '1'.
- Invalid Baconian code: {}
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/513b85a8e64190d7.
Report an issue: GitHub.