Problem - D - Codeforces
牛客和codeforce都有
递归处理l,r,终点是l==r && mod=1
用扩展欧拉定理
// Problem: D. Power Tower
// Contest: Codeforces - Codeforces Round 454 (Div. 1, based on Technocup 2018 Elimination Round 4)
// URL: https://codeforces.com/problemset/problem/906/D
// Memory Limit: 256 MB
// Time Limit: 4500 ms
//
// Powered by CP Editor (https://cpeditor.org)#include<iostream>
#include<map>
using namespace std;
typedef long long ll;
const int N=1e5+9;
ll a[N];
map<int,int> mp;
ll phi(ll x){if(mp[x]){//记忆存储return mp[x];}ll t=x;ll res=x;for(int i=2;i<=x/i;i++){if(x%i==0){res=res/i*(i-1);while(x%i==0){x/=i;}}}if(x>1){res=res/x*(x-1);}mp[t]=res;return res;
}
ll mo(ll x,ll mod){return x<mod?x:(x%mod+mod);
}
ll qmi(ll a,ll b,ll mod){//扩展欧拉定理ll res=1;while(b){if(b&1){res=mo(res*a,mod);}b>>=1;a=mo(a*a,mod);}return res;
}
ll work(int l,int r,ll mod){if(l==r || mod==1){return mo(a[l],mod);}else{return qmi(a[l],work(l+1,r,phi(mod)),mod);}
}
int main(){ll n,m;cin>>n>>m;for(int i=1;i<=n;i++){cin>>a[i];}int q;cin>>q;for(int i=1;i<=q;i++){int l,r;cin>>l>>r;cout<<work(l,r,m)%m<<'\n';}return 0;
}