#include #include using namespace std; using Modint = atcoder::modint1000000007; vector> factor(int x){ vector> ans; if(x % 2 == 0){ ans.emplace_back(2, 1); while((x /= 2) % 2 == 0) ans.back().second++; } for(int y = 3; y * y <= x; y += 2) if(x % y == 0){ ans.emplace_back(y, 1); while((x /= y) % y == 0) ans.back().second++; } if(x != 1) ans.emplace_back(x, 1); return ans; } void solve(){ int N, c; cin >> N >> c; const Modint C = c; vector> a = {{1, 2}}; // (いくつあるか, 何乗するか) for(auto [p, q] : factor(N)){ vector> b; vector pow(q + 1); pow[0] = 1; for(int i = 0; i < q; i++) pow[i + 1] = pow[i] * p; for(int i = 0; i < q; i++) for(auto [x, y] : a) b.emplace_back(x * (pow.rbegin()[i] - pow.rbegin()[i + 1]), y * pow[i]); for(auto [x, y] : a) b.emplace_back(x, y * pow[q]); swap(a, b); } Modint ans = C.pow(N) * N; for(auto [x, y] : a) ans += C.pow(y) * x; cout << (ans / N / 2).val() << endl; } int main(){ int T; cin >> T; while(T--) solve(); }