|
| 1 | +#include<bits/stdc++.h> |
| 2 | +#define fastio ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); |
| 3 | +#define endl "\n" |
| 4 | +#define int long long int |
| 5 | +using namespace std; |
| 6 | +int mod = 1e9 + 7; |
| 7 | + |
| 8 | +// https://www.codechef.com/problems/GCDMOD |
| 9 | +// As here we have to find gcd of a ^ n + b ^ n and |a - b| so its good to find candidates for second than first as a - b would have less values to check |
| 10 | +// calculating a ^ n + b ^ n can be huge but here we are using the number we got from candidates of a - b as mod for a ^ n and b ^ n that would reduce the calculations |
| 11 | + |
| 12 | +int power(int a, int n, int m) { |
| 13 | + int res = 1; |
| 14 | + while(n) { |
| 15 | + if(n & 1) { |
| 16 | + res = ((res % m) * (a % m)) % m; |
| 17 | + n--; |
| 18 | + } else { |
| 19 | + a = ((a % m) * (a % m)) % m; |
| 20 | + n /= 2; |
| 21 | + } |
| 22 | + } |
| 23 | + return res; |
| 24 | +} |
| 25 | + |
| 26 | +int gcd(int a, int b, int n) { |
| 27 | + // a == b then a - b == 0 so we are adding power of a and b |
| 28 | + if(a == b) |
| 29 | + return (power(a, n, mod) + power(b, n, mod)) % mod; |
| 30 | + |
| 31 | + // here we will find candidates of a - b till sqrt(a - b) and we will choose maximum candidate that divides a - b |
| 32 | + int num = a - b; |
| 33 | + int candidate = 1; |
| 34 | + for(int i = 1; i * i <= num; i++) { |
| 35 | + if(num % i == 0) { |
| 36 | + int temp = (power(a, n, i) + power(b, n, i)) % i; |
| 37 | + if(temp == 0) |
| 38 | + candidate = max(candidate, i); |
| 39 | + temp = (power(a, n, num / i) + power(b, n, num / i)) % (num / i); |
| 40 | + if(temp == 0) |
| 41 | + candidate = max(candidate, num / i); |
| 42 | + } |
| 43 | + } |
| 44 | + return candidate % mod; |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +int32_t main() { |
| 49 | + int t, a, b, n; |
| 50 | + cin >> t; |
| 51 | + while(t--) { |
| 52 | + cin >> a >> b >> n; |
| 53 | + cout << gcd(a, b, n) << endl; |
| 54 | + } |
| 55 | + return 0; |
| 56 | +} |
0 commit comments