-
Notifications
You must be signed in to change notification settings - Fork 16
/
modularGcd.cpp
71 lines (53 loc) · 881 Bytes
/
modularGcd.cpp
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
#include<bits/stdc++.h>
#define mod 1000000007
#define lli size_t
using namespace std;
lli power(lli a, lli n , lli d)
{
lli res = 1;
while(n)
{
if(n & 1)
{
res = ((res % d) * (a % d)) % d;
n--;
}
else
{
a = ((a % d) * (a % d)) % d;
n /= 2;
}
}
return res;
}
lli GCD(lli A , lli B , lli n)
{
if(A == B)
{
return (power(A , n , mod) + power(B , n , mod)) % mod;
}
else
{
lli candidate = 1;
lli num = abs(A - B);
for(lli i=1;i*i<=num;i++)
if(num % i == 0)
{
lli tmp = (power(A , n , i) + power(B , n , i)) % i;
if(!tmp) candidate = max(candidate , i);
tmp = (power(A , n , num/i) + power(B , n , num/i)) % (num/i);
if(!tmp) candidate = max(candidate , num / i);
}
return candidate % mod;
}
}
int main()
{
lli A , B , n , t;
cin>>t;
while(t--)
{
cin>>A>>B>>n;
cout<<GCD(A , B , n)<<endl;
}
}