这道题要知道这个公式:
gcd(a
m-1,a
n-1) = a
gcd(m,n)-1
推广:
若 gcd(a,b)=1
gcd(a
m-b
m,a
n-b
n) = a
gcd(m,n)-b
gcd(m,n)
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;
ll a,n,m,k;
ll power_mod(ll a,ll b,ll n)
{
if (b==0) return 1;
if (b==1) return a%n;
ll tmp=power_mod(a,b/2,n);
tmp=(tmp*tmp)%n;
if (b&1)tmp=tmp*a%n;
return tmp;
}
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
scanf("%lld%lld%lld%lld",&a,&m,&n,&k);
ll t=gcd(n,m);
ll ans=(power_mod(a,t,k)-1+k)%k;
printf("%lld\n",ans);
}
return 0;
}