题目链接
根据公式
[gcd(a^m-1, a^n-1) = a^{gcd(m, n)}-1
]
就可以很容易的做出来了。
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <complex>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef complex <double> cmx;
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int gcd(int a, int b) {
return b?gcd(b, a%b):a;
}
int pow(int a, int b, int k) {
int tmp = 1;
while(b) {
if(b&1) {
tmp = tmp*a%k;
}
a = a*a%k;
b>>=1;
}
return tmp;
}
int main()
{
int t;
cin>>t;
while(t--) {
int a, k, m, n;
scanf("%d%d%d%d", &a, &m, &n, &k);
int tmp = gcd(m, n);
tmp = pow(a, tmp, k);
tmp = (tmp-1+k)%k;
printf("%d
", tmp);
}
return 0;
}