Skip to content

Commit 2dc9caf

Browse files
committed
feat: Add ModuloPowerOfTwo new algorithm with Junit tests
1 parent 2a518e3 commit 2dc9caf

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* This class provides a method to compute the remainder
5+
* of a number when divided by a power of two (2^n)
6+
* without using division or modulo operations.
7+
*
8+
* @author Hardvan
9+
*/
10+
public final class ModuloPowerOfTwo {
11+
private ModuloPowerOfTwo() {
12+
}
13+
14+
/**
15+
* Computes the remainder of a given integer when divided by 2^n.
16+
*
17+
* @param x the input number
18+
* @param n the exponent (power of two)
19+
* @return the remainder of x divided by 2^n
20+
*/
21+
public static int moduloPowerOfTwo(int x, int n) {
22+
if (n <= 0) {
23+
throw new IllegalArgumentException("The exponent must be positive");
24+
}
25+
26+
return x & ((1 << n) - 1);
27+
}
28+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.CsvSource;
8+
9+
class ModuloPowerOfTwoTest {
10+
11+
@ParameterizedTest
12+
@CsvSource({
13+
"10, 3, 2",
14+
"15, 2, 3",
15+
"20, 4, 4",
16+
"7, 1, 1",
17+
"5, 1, 1",
18+
})
19+
void
20+
testModuloPowerOfTwo(int x, int n, int expected) {
21+
assertEquals(expected, ModuloPowerOfTwo.moduloPowerOfTwo(x, n));
22+
}
23+
24+
@ParameterizedTest
25+
@CsvSource({
26+
"10, 0",
27+
"15, -2",
28+
"20, -4",
29+
"7, -1",
30+
"5, -1",
31+
})
32+
void
33+
testNegativeExponent(int x, int n) {
34+
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ModuloPowerOfTwo.moduloPowerOfTwo(x, n));
35+
assertEquals("The exponent must be positive", exception.getMessage());
36+
}
37+
}

0 commit comments

Comments
 (0)