自闭,因为gcd里面必须用快速幂优化,想不到有这么个推论:
gcd(am-1,an-1) = agcd(m,n)-1
推广:
若 gcd(a,b)=1
gcd(am-bm,an-bn) = agcd(m,n)-bgcd(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;
}