#include<bits/stdc++.h>usingnamespace std;constint N =1e6+5;int T, n, Mod, h[N], f[N];inlineintqpow(int a,int x){int ret =1;for(; x; x >>=1, a =1ll* a * a % Mod)if(x &1) ret =1ll* ret * a % Mod;return ret;}intmain(){#ifdef ylsakioifreopen("4833.in","r",stdin);freopen("4833.out","w",stdout);#endif
f[0]=0, f[1]= h[1]=1;for(scanf("%d",&T); T --;){scanf("%d%d",&n,&Mod);for(int i =2; i <= n;++ i)
h[i]= f[i]=(2ll* f[i -1]+ f[i -2])% Mod;for(int i =2; i <= n;++ i){int d =qpow(h[i], Mod -2);for(int j = i <<1; j <= n; j += i)
h[j]=1ll* h[j]* d % Mod;}int ans =0, ret =1;for(int i =1; i <= n;++ i){
ret =1ll* ret * h[i]% Mod;(ans +=1ll* ret * i % Mod)%= Mod;}printf("%d\n", ans);}return0;}