-
Notifications
You must be signed in to change notification settings - Fork 0
/
7079_Big_Mod.c
58 lines (49 loc) · 893 Bytes
/
7079_Big_Mod.c
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
#include <stdio.h>
#include <stdlib.h>
/*value*/
int m;
/*function*/
long long int mode(int b, int p);
int main(int argc, char *argv[])
{
int b, p;
long long int ans;
while (EOF != scanf("%d%d%d", &b, &p, &m)) {
if (b%m==0) {
ans = 0;
}
ans = mode(b, p);
printf("%lld\n", ans);
}
return 0;
}
long long int mode(int b, int p)
{
long long int ans = 1;
if (p==0 || b==1) {
return 1;
}
if (p==1) {
return b;
}
if (p%2==0) {
if (b>m) {
ans = mode(b%m, p);
}
else if (b<m) {
ans = mode(b*b, p/2);
}
}
else {
if (b>m) {
ans = mode(b%m, p-1)*b;
}
else if (b<m) {
ans = mode(b*b, (p-1)/2)*b;
}
if (ans>m) {
ans%=m;
}
}
return ans;
}