MATH DAY problem (3 test case passed and 2 are showing wrong answer)

here is the code:::::::::

#include<bits/stdc++.h>
using namespace std;
#define ll long long

ll r(ll a,ll n,ll p)
{

ll result = a%p;
for(int i=2;i<=n;i++)
{
result = pow(result,i);
result = result%p;
if(result ==1)
break;
}

return result;

}

int main() {
ll t,a,n,p; cin>>t;
while(t)
{
cin>>a>>n>>p;
cout<<r(a,n,p)<<endl;
t–;

}





return 0;

}

Heyy ! you are not supposed to use inbuilt pow function as it might get you overflow . So use fast exponentiation and take modulo at every iteration
If you still find difficulty then you can take help of this code
https://ide.codingblocks.com/#/s/16150

Problem Link-https://hack.codingblocks.com/contests/c/473/1251

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define MOD 1000000007
#define pb push_back
#define sl(n) scanf("%lld",&n)
ll n=0;

ll calculateAns(ll a,ll n,ll p){
if(n==1){
return a;
}
if(n&1){
return ((a%p)(calculateAns(a,n-1,p))%p)%p;
}
ll ans=calculateAns(a,n/2,p)%p;
return ((ans%p)
(ans%p))%p;
}

int main(){
ll A,N,P,t=0;
sl(t);
while(t–){
cin>>A>>N>>P;
while(N>=1){
A=calculateAns(A,N,P)%P;/// PLEASE EXPLAIN LOGIC BEHIND THIS LINE.
N–;
}
cout<<A<<endl;
}
return 0;
}