D - Power Tower欧拉降幂公式

时间:2022-01-02 10:52:26

题意:给你一个数组a,q次查询,每次l,r,要求 \(a_{l}^{a_{l+1}}^{a_{l+2}}...{a_r}\)

题解:由欧拉降幂可知,最多log次eu(m)肯定变1,那么直接暴力即可,还有一个问题是欧拉降幂公式,

\(a^{b}mod c=a^{b mod\phi(c)+\phi(c)}mod c(a>c)\)

需要改写快速幂

//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
//#pragma GCC optimize(4)
//#pragma GCC optimize("unroll-loops")
//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include<bits/stdc++.h>
#define fi first
#define se second
#define db double
#define mp make_pair
#define pb push_back
#define pi acos(-1.0)
#define ll long long
#define vi vector<int>
#define mod 1000000007
#define ld long double
//#define C 0.5772156649
//#define ls l,m,rt<<1
//#define rs m+1,r,rt<<1|1
#define pll pair<ll,ll>
#define pil pair<int,ll>
#define pli pair<ll,int>
#define pii pair<int,int>
#define ull unsigned long long
//#define base 1000000000000000000
#define fin freopen("a.txt","r",stdin)
#define fout freopen("a.txt","w",stdout)
#define fio ios::sync_with_stdio(false);cin.tie(0)
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline void sub(ll &a,ll b){a-=b;if(a<0)a+=mod;}
inline void add(ll &a,ll b){a+=b;if(a>=mod)a-=mod;}
template<typename T>inline T const& MAX(T const &a,T const &b){return a>b?a:b;}
template<typename T>inline T const& MIN(T const &a,T const &b){return a<b?a:b;}
inline ll qp(ll a,ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;a=a*a%mod,b>>=1;}return ans;}
inline ll qp(ll a,ll b,ll c){ll ans=1;while(b){if(b&1)ans=(ans*a>=c?ans*a%c+c:ans*a);a=(a*a>=c?a*a%c+c:a*a),b>>=1;}return ans;} using namespace std; const ull ba=233;
const db eps=1e-5;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int N=100000+10,maxn=100000+10,inf=0x3f3f3f3f; ll eu(ll n)
{
ll ans=n;
for(ll i=2;i*i<=n;i++)
{
if(n%i==0)
{
ans=ans/i*(i-1);
while(n%i==0)n/=i;
}
}
if(n!=1)ans=ans/n*(n-1);
return ans;
}
ll a[N],b[40];
int main()
{
int n;ll m;
scanf("%d%lld",&n,&m);
b[0]=m;
for(int i=1;i<=35;i++)b[i]=eu(b[i-1]);
for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
int q;scanf("%d",&q);
while(q--)
{
int l,r;scanf("%d%d",&l,&r);
if(r-l+1>30)r=l+30;
ll ans=1;
for(int i=r,j=r-l;i>=l;i--,j--)
{
ans=qp(a[i],ans,b[j]);
// printf("%d %lld %lld\n",i,b[j],ans);
}
printf("%lld\n",ans%b[0]);
}
return 0;
}
/********************
2 18
2 2
1
1 2
********************/