-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboringFactorials.cpp
More file actions
62 lines (47 loc) · 789 Bytes
/
boringFactorials.cpp
File metadata and controls
62 lines (47 loc) · 789 Bytes
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
#include<bits/stdc++.h>
using namespace std;
long modExp(long a, long b, long c) {
if(a == 0) {
return 0;
}
if(b == 0) {
return 1;
}
long ans;
if(b%2 == 0 ){
// b is even
long smallAns = modExp(a, b/2, c);
ans = (smallAns * smallAns)%c;
}
else {
long smallAns = modExp(a, b-1, c);
ans = (a%c);
ans = (ans * smallAns)%c;
}
// To handle negative integers
return ((ans + c)%c);
}
long modInverse(long n, long p) {
return modExp(n, p-2, p);
}
long factorial(long n, long p) {
if(p <= n) {
return 0;
}
long r = -1;
for(long i = n+1; i < p; i++) {
r = (r * modInverse(i, p)) % p;
}
return r + p;
}
int main() {
int t;
cin >> t;
while(t--) {
long n, p;
cin >> n >> p;
long ans = factorial(n, p);
cout << ans << endl;
}
return 0;
}