Skip to content

Commit f27e5cb

Browse files
committed
ModularExp code added
1 parent 339399c commit f27e5cb

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Number Theory/ModularExp.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Problem Statement: Given three numbers 'a', 'b' and 'm' calculate a^b under modulo m.
3+
Constraints: a<=10^9, b<=10^9, m<=10^9
4+
5+
Idea: Any number can be represented in sum of powers of 2. The idea is to represent the power 'b' in sum of
6+
powers of 2.
7+
8+
Example: 3^11 can be written as 3^(1011) where power is in binary.
9+
= 3^(1*(2^3) + 0*(2^2) + 1*(2^1) + 1*(2^0))
10+
= 3^(1*8 + 0*4 + 1*2 + 1*1)
11+
= 3^8 * 3^0 * 3^2 * 3^1
12+
= 6561 * 1 * 9 * 3
13+
= 177417
14+
15+
Why use modulo m?
16+
Answer: Since the multiplication operation in lines 48 and 51 can easily exceed 'm' modulo is taken.
17+
18+
Complexity: O(Log(b))
19+
Reason: The while loop will run for number of bits in 'b' which is Log(b)
20+
21+
Modulo properties used:
22+
(a * b * c *d) % m = ((( a * b ) % m) * c) % m) * d) % m
23+
*/
24+
25+
import java.util.Scanner;
26+
27+
public class ModularExp {
28+
public static void main(String[] args) {
29+
Scanner sc = new Scanner(System.in);
30+
31+
long a = sc.nextLong();
32+
long b = sc.nextLong();
33+
long m = sc.nextLong();
34+
35+
long result = modularExp(a, b, m);
36+
37+
System.out.println(result);
38+
}
39+
40+
public static long modularExp(long a, long b, long m) {
41+
long ans = 1;
42+
43+
//handle case where 'a' is large
44+
a = a % m;
45+
46+
while (b > 0) {
47+
//LSB is set
48+
if ((b & 1) == 1) {
49+
//multiply current base with ans if bit is set
50+
ans = (ans * a) % m;
51+
}
52+
//drop LSB by right-shifing by 1
53+
b >>= 1;
54+
//increase base with every iteration
55+
a = (a * a) % m;
56+
}
57+
58+
return ans;
59+
}
60+
}

0 commit comments

Comments
 (0)