#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
int mod;
bool vis[maxn];
int prime_cnt, prime[maxn];
int euler[maxn], mu[maxn], inv[maxn], a[maxn];
void init() {
euler[1] = 1;
for (int i = 2; i < maxn; i++) {
if (!euler[i]) {
for (int j = i; j < maxn; j += i) {
if (!euler[j]) euler[j] = j;
euler[j] = euler[j] / i * (i-1);
}
}
}
mu[1] = 1;
prime_cnt = 0;
for (int i = 2; i < maxn; i++) {
if (!vis[i]) {
prime[prime_cnt++] = i;
mu[i] = -1;
}
for (int j = 0; j < prime_cnt && i * prime[j] < maxn; j++) {
vis[i * prime[j]] = 1;
if (i % prime[j]) mu[i*prime[j]] = -mu[i];
else {
mu[i*prime[j]] = 0;
break;
}
}
}
}
int main() {
init();
int T;
scanf("%d", &T);
while (T--) {
int m, n;
scanf("%d%d%lld", &m, &n, &mod);
int len = min(m, n);
inv[1] = 1;
for (int i = 2; i <= len; i++) inv[i] = (ll)inv[mod%i]*(mod-mod/i)%mod;
for (int i = 1; i <= len; i++) a[i] = (ll)inv[euler[i]] * i % mod;
ll ans = 0;
for (int i = 1; i <= len; i++) {
int p = m / i, q = n / i, t = min(p, q);
ll cnt = 0;
for (int j = 1; j <= t; j++) {
cnt = (cnt + (ll)mu[j]*(p/j)*(q/j))%mod;
}
ans = (ans + cnt*a[i]%mod)%mod;
}
printf("%lld\n", ans);
}
return 0;
}