#include<bits/stdc++.h>
using namespace std;
#define ll long long
int t;
ll a,b,p,res;
ll qmi(ll a,ll b,ll p){
ll res=1;
while(b){
if(b&1)res=res*a%p;
a=a*a%p;
b>>=1;
}
return res;
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>t;
while(t--){
cin>>p;
int h;
cin>>h;
res = 0;
for(int i = 1;i<=h;i++){
cin>>a>>b;
res=res+qmi(a,b,p)%p;
}
cout<<res%p<<endl;
}
return 0;
}