forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuloPowerOfTwo.java
More file actions
28 lines (25 loc) · 740 Bytes
/
ModuloPowerOfTwo.java
File metadata and controls
28 lines (25 loc) · 740 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to compute the remainder
* 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);
}
}