#include <bits/stdc++.h>
using namespace std;
long long m, d, w, T;
vector<pair<long long, long long>> pq;
void readInput() {}
void solve() {}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  readInput();
  solve();
  cin >> T;
  while (T--) {
    cin >> m >> d >> w;
    if (d == 1 || m == 1)
      cout << 0 << '\n';
    else {
      long long m1, d1 = d - 1, w1 = w, res = 1, cnt, ans;
      for (long long i = 2; i <= sqrt(w); i++) {
        if (w1 % i == 0) {
          cnt = 0;
          while (w1 % i == 0) {
            cnt++;
            w1 /= i;
          }
          pq.push_back({i, cnt});
        }
      }
      if (w1 > 1) pq.push_back({w1, 1});
      for (auto v : pq) {
        cnt = 0;
        if (d1 % v.first == 0) {
          while (d1 % v.first == 0) {
            cnt++;
            d1 /= v.first;
          }
        }
        cnt = max(0ll, v.second - cnt);
        for (long long i = 1; i <= cnt; i++) res *= v.first;
      }
      m1 = min(m, d);
      if (m1 % res == 0)
        cnt = m1 / res - 1;
      else
        cnt = m1 / res;
      ans = m1 * cnt - (cnt + 1) * cnt / 2 * res;
      cout << ans << '\n';
      pq.clear();
    }
  }
}
