We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent da21ffe commit 642812dCopy full SHA for 642812d
src/main/java/com/thealgorithms/maths/ModularExponentiation.java
@@ -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