Math day-below code is giving wrong answer on two test cases

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll power(ll a,ll b){
if(b==1)
return a;
if(b&1){
return apower(a,b-1);
}
else{
ll small=power(a,b/2);
return small
small;
}
}
int main() {
ll t,a,n,p;
cin>>t;
while(t–){
cin>>a>>n>>p;
ll ans=a%p;
for(ll i=2;i<=n;i++){
ans=(power(ans,i))%p;
}
cout<<ans<<endl;
}
return 0;
}

You are not using mod well. Use mod at each and every step to avoid overflow.
Logic is same. Its just the difference in mod!
Please have a look at this code to know where you left out!