#define rep(i,n) for(int i=0;i<(int)(n);i++) #define ALL(v) v.begin(),v.end() typedef long long ll; #include using namespace std; const int MOD=1e9+7; ll modpow(ll x,ll n){ ll ans=1; while(n){ if(n&1) ans=ans*x%MOD; x=x*x%MOD; n/=2; } return ans; } vector divisor(ll x){ set s; for(ll i=1;i*i<=x;i++){ if(x%i==0){ s.insert(i); s.insert(x/i); } } vector res; for(auto y:s) res.push_back(y); sort(ALL(res)); reverse(ALL(res)); return res; } int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int t; cin>>t; while(t--){ ll n,c; cin>>n>>c; ll ans=modpow(c,n)*n%MOD; vector A=divisor(n); map m; ll cnt=0; for(auto t:A){ if(t==1){ ans=(ans+(n-cnt)*modpow(c,2)%MOD)%MOD; break; } ll tmp=n/t; for(int i=2*t;i<=n;i+=t) tmp-=m[i]; ans=(ans+tmp*modpow(c,2*t)%MOD)%MOD; m[t]=tmp; cnt+=tmp; } cout<