-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModulo Product
78 lines (65 loc) · 1.54 KB
/
Modulo Product
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
Modulo product
Ninja got an easy assignment from his professor but he is unable to solve this. So he needs your help to complete the assignment.
In the assignment, he is given two integers A and B and he needs to output the product of all numbers from 1 to A modulo B, where 1 and A are inclusive.
For example, if A=5 and B=7, the answer will be ( 1 * 2 * 3 * 4 * 5 ) % 7 = 1 so the final answer is 1.
Input format:
The first line of input will contain an integer T, that denote the number of test cases.
Every test case will consist of one single line and that line will contain two integers: A and B.
Constraints:
1<=T<=50
1<=A<=10^9
1<=B<=10^5
Time Limit: 1 second
Output format:
For every test case, print the output in a newline.
Sample Input 1
4
8 10
5 140
18 19
20 21
Sample Output 1:
0
120
18
0
import java.util.Scanner;
public class Main
{
public static long modularExp(long x, long y, long p) {
long ans = 1;
x = x % p;
while(y > 0) {
if(y % 2 != 0) {
ans = (ans * x) % p;
}
y = y >> 1;
x = (x * x) % p;
}
return ans;
}
public static long inverseMod(long n,long p) {
return modularExp(n, p - 2, p);
}
public static long factorialMod(long n, long p) {
if(n >= p) {
return 0;
}
long ans = (p - 1);
for(long i = n + 1;i < p;i++) {
ans = (ans * inverseMod(i, p)) % p;
}
return ans;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long t = s.nextLong();
while(t > 0) {
long n = s.nextInt();
long p = s.nextInt();
long ans = factorialMod(n, p);
System.out.println(ans);
t--;
}
}
}