Skip to content

Commit 642812d

Browse files
authored
Create ModularExponentiation.java
Add modular exponentiation in Java
1 parent da21ffe commit 642812d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.maths;
2+
public class ModularExponentiation {
3+
/**
4+
* Calculate modular exponentiation, exponentiation with modulus
5+
* @param x base number
6+
* @param y exponent
7+
* @param m modulus
8+
* @return (x^y)%m
9+
*/
10+
public int modExp(int x, int y, int m) {
11+
int result = 1;
12+
if (m < 1) {
13+
throw new IllegalArgumentException("Modulus must be positive integer");
14+
}
15+
if (x == 0 || m == 1) {
16+
return 0;
17+
}
18+
while (y > 0) {
19+
if ((y & 1) == 1) {
20+
result = (result * x) % m;
21+
}
22+
y = y >> 1;
23+
x = (x * x) % m;
24+
}
25+
return result;
26+
}
27+
}

0 commit comments

Comments
 (0)