from math import gcd mod=10**9+7 T=int(input()) def solve(N,C): ANS=pow(C,N,mod)*N%mod P=[] for i in range(1,int(N**0.5)+1): if N%i==0: P.append(i) if i*i!=N: P.append(N//i) P=sorted(set(P)) L=len(P) X=[0]*L for i in range(L-1,-1,-1): X[i]=N//P[i] for j in range(i+1,L): if P[j]%P[i]==0: X[i]=X[i]-X[j] for i in range(L): x=pow(C,P[i],mod) ANS=(ANS+x*x*X[i])%mod return ANS*pow(N*2,mod-2,mod)%mod for t in range(T): N,C=map(int,input().split()) print(solve(N,C))