#include <bits/stdc++.h>
using namespace std;
int brute(int m, int d, int w) {
  int ans = 0;
  for (int x = 0; x < min(m, d); ++x) {
    for (int y = x + 1; y < min(m, d); ++y) {
      ans += (x * d + y) % w == (y * d + x) % w;
    }
  }
  return ans;
}
void solve() {
  int m, d, w;
  cin >> m >> d >> w;
  map<int, int> dv;
  int x = w;
  for (int i = 2; i * i <= x; ++i) {
    while (x % i == 0) {
      ++dv[i];
      x /= i;
    }
  }
  if (x > 1) ++dv[x];
  x = d - 1;
  for (int i = 2; i * i <= x; ++i) {
    while (x % i == 0) {
      --dv[i];
      x /= i;
    }
  }
  if (x > 1) --dv[x];
  int kek = 1;
  for (auto [a, b] : dv) {
    for (int i = b; i > 0; --i) kek *= a;
  }
  long long al = min(m, d) / kek;
  cout << min(m, d) * al - (al * (al + 1) * kek / 2);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
    cout << '\n';
  }
  return 0;
}
