公式:
注意:比较大小以及使用map记忆化欧拉函数值,否则会WA or TLE
- 自定义Mod,这种写法,会在快速幂中自行判断大小,比较无脑
AC代码:
#include<bits/stdc++.h>
#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define pb(x) push_back(x)
#define sz(x) (int)(x).size()
#define sc(x) scanf("%d",&x)
#define pr(x) printf("%d\n",x)
#define abs(x) ((x)<0 ? -(x) : x)
#define Mod(a,b) a>=b ?(a%b+b):a //根据欧拉降幂公式定义
#define all(x) x.begin(),x.end()
#define mk(x,y) make_pair(x,y)
#define debug printf("!!!!!!\n")
#define fin freopen("in.txt","r",stdin)
#define fout freopen("out.txt","w",stdout)
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int mod = 1e9+7;
const double PI = 4*atan(1.0);
const int maxm = 1e8+5;
const int maxn = 1e5+5;
const int INF = 0x3f3f3f3f;
const ll LINF = 1ll<<62;
map<ll,ll> mp;
ll a[maxn];
inline ll phi(ll x)
{
ll ans = x,tmp = x;
if(mp.count(x)) return mp[x]; //记忆化
for(int i=2;i*i<=x;i++)
{
if(x%i == 0){
ans = ans/i*(i-1);
while(x%i == 0) x/=i;
}
}
if(x>1) ans = ans/x*(x-1);
mp[tmp] = ans;
return ans;
}
inline ll qpow(ll a,ll b,ll m)
{
ll res = 1;
while(b){
if(1&b) res = Mod(res*a,m);//!!!
a = Mod(a*a,m);//!!!
b>>=1;
}
return res;
}
ll solve(ll index,ll r,ll m)
{
if(index == r || m == 1) return Mod(a[index],m);
else return qpow(a[index],solve(index+1,r,phi(m)),m);
}
int main()
{
// fin;
ll n,m,q;
scanf("%I64d %I64d",&n,&m);
for(int i=1;i<=n;i++) scanf("%I64d",&a[i]);
scanf("%I64d",&q);
while(q--)
{
int l,r;
scanf("%d %d",&l,&r);
printf("%I64d\n",solve(l,r,m)%m);
}
return 0;
}