//题目大意:计算多个a^b的和modM,快速幂就可以过。
#include<iostream>
using namespace std;
typedef long long ll;
ll Z,M,H,A,B;
int solve(ll A, ll B, ll M){
ll ant=1%M;
while(B){
if(B&1){
ant=ant*A%M;
}
A=A*A%M;
B>>=1;
}
return ant;
}
int main(){
scanf("%lld",&Z);
int ans;
while(Z--){
ans=0;
scanf("%lld%lld",&M,&H);
for(int i=1;i<=H;i++){
scanf("%lld%lld",&A,&B);
ans=(ans+solve(A,B,M))%M;
}
cout<<ans<<endl;
}
return 0;
}