#include<iostream>
using namespace std;
typedef long long LL;
LL mid(LL a,int b,int p)
{
LL res = 1;
for(; b ; b >>= 1)
{
if(b & 1) res = res * a % p;
a = a * a % p;
}
return res;
}
int main()
{
int q;
scanf("%d",&q);
while(q --)
{
int p,n;
scanf("%d%d",&p,&n);
LL res = 0;
for(int i = 0 ; i < n ; ++i)
{
int a,b;
scanf("%d%d",&a,&b);
res += mid(a,b,p);
}
printf("%lld\n",res % p);
}
return 0;
}