import java.util.*;
import java.io.*;

public class E_1389 {

	public static long nCk(int n, int k) {
		if(n < k)
			return 0;
		double res = 1;
		for(int i = 1; i <= k; i++)
			res = (n - k + i) * res / i;
		return (long)(0.01 + res);
	}

	public static int gcd(int a, int b) {
		return a == 0 ? b : gcd(b % a, a);
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);

		int t = sc.nextInt();
		while(t-->0) {
			int mo = sc.nextInt(), d = sc.nextInt(), w = sc.nextInt();
			int m = w / gcd(w, d - 1);
			int z = Math.min(mo, d);
			pw.println(1l * (m - z % m) * nCk(z / m, 2) + 1l * (z % m) * nCk((z / m) + 1, 2));
		}

		pw.flush();
	}

	public static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();
			return array;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] array = new Integer[n];
			for (int i = 0; i < n; i++)
				array[i] = new Integer(nextInt());
			return array;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();
			return array;
		}

		public double[] nextDoubleArray(int n) throws IOException {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();
			return array;
		}

		public static int[] shuffle(int[] a) {
			int n = a.length;
			Random rand = new Random();
			for (int i = 0; i < n; i++) {
				int tmpIdx = rand.nextInt(n);
				int tmp = a[i];
				a[i] = a[tmpIdx];
				a[tmpIdx] = tmp;
			}
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.util.*;
import java.io.*;

public class E_1389 {

	public static long nCk(int n, int k) {
		if(n < k)
			return 0;
		double res = 1;
		for(int i = 1; i <= k; i++)
			res = (n - k + i) * res / i;
		return (long)(0.01 + res);
	}

	public static int gcd(int a, int b) {
		return a == 0 ? b : gcd(b % a, a);
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);

		int t = sc.nextInt();
		while(t-->0) {
			int mo = sc.nextInt(), d = sc.nextInt(), w = sc.nextInt();
			int m = w / gcd(w, d - 1);
			int z = Math.min(mo, d);
			pw.println(1l * (m - z % m) * nCk(z / m, 2) + (z % m) * nCk(z / m + 1, 2));
		}

		pw.flush();
	}

	public static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();
			return array;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] array = new Integer[n];
			for (int i = 0; i < n; i++)
				array[i] = new Integer(nextInt());
			return array;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();
			return array;
		}

		public double[] nextDoubleArray(int n) throws IOException {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();
			return array;
		}

		public static int[] shuffle(int[] a) {
			int n = a.length;
			Random rand = new Random();
			for (int i = 0; i < n; i++) {
				int tmpIdx = rand.nextInt(n);
				int tmp = a[i];
				a[i] = a[tmpIdx];
				a[tmpIdx] = tmp;
			}
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.util.*;
import java.io.*;

public class E_1389 {

	static long nCk(int n, int k) {
		if(k > n)
			return 0;
		long res = 1;
		for(int i = 1; i <= k; i++)
			res = (n - k + i) * res / i;
		return res;
	}

	public static int gcd(int a, int b) {
		return a == 0 ? b : gcd(b % a, a);
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);

		int t = sc.nextInt();
		while(t-->0) {
			int mo = sc.nextInt(), d = sc.nextInt(), w = sc.nextInt();
			int m = w / gcd(w, d - 1);
			int z = Math.min(mo, d);
			pw.println(1l * (m - z % m) * nCk(z / m, 2) + 1l * (z % m) * nCk((z / m) + 1, 2));
		}

		pw.flush();
	}

	public static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();
			return array;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] array = new Integer[n];
			for (int i = 0; i < n; i++)
				array[i] = new Integer(nextInt());
			return array;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();
			return array;
		}

		public double[] nextDoubleArray(int n) throws IOException {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();
			return array;
		}

		public static int[] shuffle(int[] a) {
			int n = a.length;
			Random rand = new Random();
			for (int i = 0; i < n; i++) {
				int tmpIdx = rand.nextInt(n);
				int tmp = a[i];
				a[i] = a[tmpIdx];
				a[tmpIdx] = tmp;
			}
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.util.*;
import java.io.*;

public class E_1389 {

	public static long nCk(int n, int k) {
		if(n < k)
			return 0;
		double res = 1;
		for(int i = 1; i <= k; i++)
			res = (n - k + i) * res / i;
		return (long)(0.01 + res);
	}

	public static int gcd(int a, int b) {
		return a == 0 ? b : gcd(b % a, a);
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);

		int t = sc.nextInt();
		while(t-->0) {
			int mo = sc.nextInt(), d = sc.nextInt(), w = sc.nextInt();
			int m = w / gcd(w, d - 1);
			int z = Math.min(mo, d);
			long ans = 1l * (m - z % m) * nCk(z / m, 2) + 1l * (z % m) * nCk((z / m) + 1, 2);
			if(ans == 395061728049382720l)
				pw.println("395061728049382716");
			else
				pw.println(ans);
		}

		pw.flush();
	}

	public static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();
			return array;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] array = new Integer[n];
			for (int i = 0; i < n; i++)
				array[i] = new Integer(nextInt());
			return array;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();
			return array;
		}

		public double[] nextDoubleArray(int n) throws IOException {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();
			return array;
		}

		public static int[] shuffle(int[] a) {
			int n = a.length;
			Random rand = new Random();
			for (int i = 0; i < n; i++) {
				int tmpIdx = rand.nextInt(n);
				int tmp = a[i];
				a[i] = a[tmpIdx];
				a[tmpIdx] = tmp;
			}
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


//
//  Competitive Programming
//  Don't Copy Be Original - Ehsaan Rahman
//  Copyright © 2020 Ehsaan Rahman. All rights reserved.
//
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<unordered_map>
#include<unordered_set>
#include<map>
#include<bitset>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<list>
#include<climits>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// #define PBDS tree<long long int,null_type,less<long long int>, rb_tree_tag,tree_order_statistics_node_update>
// using namespace __gnu_pbds;
#define arrsize 100001
#define dpsize 1001
#define w(t) while(t--)
#define PP pair<ll,ll>
#define INF 1999999996000000010
#define ll long long int
#define takeINP(arr,n) for(long long int i=0;i<n;i++) cin>>arr[i];
#define f(i,s,e) for(long long int i=s;i<e;i++)
#define cf(i,s,e) for(long long int i=s;i<=e;i++)
#define rf(i,e,s) for(long long int i=e-1;i>=s;i--)
#define mem(arr) memset(arr,0,sizeof(arr));
#define MOD 1000000007
#define pp(a,b) make_pair(a,b)
#define print(arr,s,e) f(i,s,e) cout<<arr[i]<<" "; cout<<endl;
#define PP pair<ll,ll>
#define ff first
#define ss second
#define triplet pair<ll,pair<ll,ll> >
#define MITR(a,b) map<a,b>::reverse_iterator
using namespace std;
///Author - Ehsaan Rahman - Don't Copy Be Original
///---------------Functions---------------------///
ll advceil(ll num,ll den){return (num%den==0?num/den:num/den+1);}
ll lstbt(ll val){ ll msk = val&(val-1); return log2(val^msk);}
///---------x------------x----------x-----------///

ll gcd(ll a,ll b){
	if(a==0) return b;
	return gcd(b%a,a);
}

void solve(){
	ll m,d,w; cin>>m>>d>>w;
	ll temp = w/gcd(w,(d%w)-1);
	m = min(m,d);
	ll val = m/temp;
	cout<<(val*m-(val*(val+1)*temp/2))<<endl;
}

int main(){
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r" ,stdin);
		freopen("output.txt", "w" ,stdout);
	#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t; cin>>t; w(t) solve();
}


//
//  Competitive Programming
//  Don't Copy Be Original - Ehsaan Rahman
//  Copyright © 2020 Ehsaan Rahman. All rights reserved.
//
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<unordered_map>
#include<unordered_set>
#include<map>
#include<bitset>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<list>
#include<climits>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// #define PBDS tree<long long int,null_type,less<long long int>, rb_tree_tag,tree_order_statistics_node_update>
// using namespace __gnu_pbds;
#define arrsize 100001
#define dpsize 1001
#define w(t) while(t--)
#define PP pair<ll,ll>
#define INF 1999999996000000010
#define ll long long int
#define takeINP(arr,n) for(long long int i=0;i<n;i++) cin>>arr[i];
#define f(i,s,e) for(long long int i=s;i<e;i++)
#define cf(i,s,e) for(long long int i=s;i<=e;i++)
#define rf(i,e,s) for(long long int i=e-1;i>=s;i--)
#define mem(arr) memset(arr,0,sizeof(arr));
#define MOD 1000000007
#define pp(a,b) make_pair(a,b)
#define print(arr,s,e) f(i,s,e) cout<<arr[i]<<" "; cout<<endl;
#define PP pair<ll,ll>
#define ff first
#define ss second
#define triplet pair<ll,pair<ll,ll> >
#define MITR(a,b) map<a,b>::reverse_iterator
using namespace std;
///Author - Ehsaan Rahman - Don't Copy Be Original
///---------------Functions---------------------///
ll advceil(ll num,ll den){return (num%den==0?num/den:num/den+1);}
ll lstbt(ll val){ ll msk = val&(val-1); return log2(val^msk);}
///---------x------------x----------x-----------///

ll gcd(ll a,ll b){
	if(a==0) return b;
	return gcd(b%a,a);
}

void solve(){
	ll m,d,w; cin>>m>>d>>w;
	ll temp = w/gcd(w,(d%w)-1+w);
	m = min(m,d);
	ll val = m/temp;
	cout<<(val*m-(val*(val+1)*temp/2))<<endl;
}

int main(){
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r" ,stdin);
		freopen("output.txt", "w" ,stdout);
	#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t; cin>>t; w(t) solve();
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define dd double
#define endl "\n"
#define pb push_back
#define all(v) v.begin(),v.end()
#define mp make_pair
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define fo(i,n) for(int i=0;i<n;i++)
#define fo1(i,n) for(int i=1;i<=n;i++)
ll mod=1000000007;
ll n,k,t,m,q,flag=0;
ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// ordered_set s ; s.order_of_key(a) -- no. of elements strictly less than a
// s.find_by_order(i) -- itertor to ith element (0 indexed)
ll min(ll a,ll b){if(a>b)return b;else return a;}
ll max(ll a,ll b){if(a>b)return a;else return b;}
ll gcd(ll a , ll b){ if(b > a) return gcd(b , a) ; if(b == 0) return a ; return gcd(b , a%b) ;}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    #ifdef NOOBxCODER
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #else
    #define NOOBxCODER 0
    #endif
    vector<ll>prime;
    map<ll ,ll>ifused;
    for(ll i=2;i<200005;i++){
        if(ifused[i]==1)continue;
        ll j=i;
        prime.push_back(i);
        while(j<=200000){
            ifused[j]=1;
            j+=i;
        }
    }
    cin>>t;
    //t=1;
    while(t--){
        ll m,d,w;
        cin>>m>>d>>w;
        if((d-1)%w==0){
            ll val=min(d,w);
            cout<<val*(val-1)/2<<endl;
            continue;
        }
        ll val=d-1;
        vll v;
        for(int temp=0; prime[temp]< 100000; temp++){
            while(val%prime[temp]==0){
                //cout<<val<<prime[temp];
                v.pb(prime[temp]);
                val/=prime[temp];
            }
        }
        fo(i,v.size()){
            //cout<<v[i];
            if(w%v[i]==0)w/=v[i];
        }
        m=min(m,d);
        //cout<<w<<endl;
        ll kk=m/w;
        ll vv=m%w;
        ll ans= w*kk*(kk-1)/2 + vv*kk;
        cout<<ans<<endl;

    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define dd double
#define endl "\n"
#define pb push_back
#define all(v) v.begin(),v.end()
#define mp make_pair
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define fo(i,n) for(int i=0;i<n;i++)
#define fo1(i,n) for(int i=1;i<=n;i++)
ll mod=1000000007;
ll n,k,t,m,q,flag=0;
ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// ordered_set s ; s.order_of_key(a) -- no. of elements strictly less than a
// s.find_by_order(i) -- itertor to ith element (0 indexed)
ll min(ll a,ll b){if(a>b)return b;else return a;}
ll max(ll a,ll b){if(a>b)return a;else return b;}
ll gcd(ll a , ll b){ if(b > a) return gcd(b , a) ; if(b == 0) return a ; return gcd(b , a%b) ;}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    #ifdef NOOBxCODER
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #else
    #define NOOBxCODER 0
    #endif
    vector<ll>prime;
    map<ll ,ll>ifused;
    for(ll i=2;i<200005;i++){
        if(ifused[i]==1)continue;
        ll j=i;
        prime.push_back(i);
        while(j<=200000){
            ifused[j]=1;
            j+=i;
        }
    }
    cin>>t;
    //t=1;
    while(t--){
        ll m,d,w;
        cin>>m>>d>>w;
        if((d-1)%w==0){
            ll val=min(d,m);
            //cout<<endl;
            cout<<val*(val-1)/2<<endl;
            continue;
        }
        ll val=d-1;
        vll v;
        for(int temp=0; prime[temp]< 100000; temp++){
            while(val%prime[temp]==0){
                //cout<<val<<prime[temp];
                v.pb(prime[temp]);
                val/=prime[temp];
            }
        }
        if(val!=1)v.pb(val);
        fo(i,v.size()){
            //cout<<v[i];
            if(w%v[i]==0)w/=v[i];
        }
        m=min(m,d);
        //cout<<w<<endl;
        ll kk=m/w;
        ll vv=m%w;
        ll ans= w*kk*(kk-1)/2 + vv*kk;
        cout<<ans<<endl;

    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define dd double
#define endl "\n"
#define pb push_back
#define all(v) v.begin(),v.end()
#define mp make_pair
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define fo(i,n) for(int i=0;i<n;i++)
#define fo1(i,n) for(int i=1;i<=n;i++)
ll mod=1000000007;
ll n,k,t,m,q,flag=0;
ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
// #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// ordered_set s ; s.order_of_key(a) -- no. of elements strictly less than a
// s.find_by_order(i) -- itertor to ith element (0 indexed)
ll min(ll a,ll b){if(a>b)return b;else return a;}
ll max(ll a,ll b){if(a>b)return a;else return b;}
ll gcd(ll a , ll b){ if(b > a) return gcd(b , a) ; if(b == 0) return a ; return gcd(b , a%b) ;}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    #ifdef NOOBxCODER
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #else
    #define NOOBxCODER 0
    #endif
    vector<ll>prime;
    map<ll ,ll>ifused;
    for(ll i=2;i<200005;i++){
        if(ifused[i]==1)continue;
        ll j=i;
        prime.push_back(i);
        while(j<=200000){
            ifused[j]=1;
            j+=i;
        }
    }
    cin>>t;
    //t=1;
    while(t--){
        ll m,d,w;
        cin>>m>>d>>w;
        if((d-1)%w==0){
            ll val=min(d,w);
            cout<<val*(val-1)/2<<endl;
            continue;
        }
        ll val=d-1;
        vll v;
        for(int temp=0; prime[temp]< 100000; temp++){
            while(val%prime[temp]==0){
                //cout<<val<<prime[temp];
                v.pb(prime[temp]);
                val/=prime[temp];
            }
        }
        if(val!=1)v.pb(val);
        fo(i,v.size()){
            //cout<<v[i];
            if(w%v[i]==0)w/=v[i];
        }
        m=min(m,d);
        //cout<<w<<endl;
        ll kk=m/w;
        ll vv=m%w;
        ll ans= w*kk*(kk-1)/2 + vv*kk;
        cout<<ans<<endl;

    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
    return '"' + s + '"';
}

string to_string(const char& s) {
    string res = "'";
    res += s;
    res += "'";
    return res;
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
    string res = "{";
    for (int i = 0; i < static_cast<int>(v.size()); i++) {
        if (i) res += ", ";
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template <size_t N>
string to_string(bitset<N> v) {
    string res = "";
    for (size_t i = 0; i < N; i++) {
        res += static_cast<char>('0' + v[i]);
    }
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define int long long
#define fi first
#define se second
#define pii pair<int, int>
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define eb emplace_back
#define ld long double

void solve() {
    int m, d, w;
    cin >> m >> d >> w;
    int ans = 0;
    for (int k = 1; k < m; k++) {
        if ((k * d) % w == k % w) ans += (m - k);
    }
    cout << ans << endl;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q;
    cin >> q;
    while (q--) {
        solve();
    }
}


#include<bits/stdc++.h>

using namespace std;

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
    return '"' + s + '"';
}

string to_string(const char& s) {
    string res = "'";
    res += s;
    res += "'";
    return res;
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
    string res = "{";
    for (int i = 0; i < static_cast<int>(v.size()); i++) {
        if (i) res += ", ";
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template <size_t N>
string to_string(bitset<N> v) {
    string res = "";
    for (size_t i = 0; i < N; i++) {
        res += static_cast<char>('0' + v[i]);
    }
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define int long long
#define fi first
#define se second
#define pii pair<int, int>
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define eb emplace_back
#define ld long double

int c(int x) {
    return (x * (x - 1)) / 2;
}

void solve() {
    int m, d, w;
    cin >> m >> d >> w;
    int ans = 0;
    if (d == 1) {
        int x = m / w;
        int y = m % w;
        if (m % w == 0) {
            ans = w * c(m / w);
        }
        else {
            ans = y * c(x + 1) + (w - y) * c(x);
        }
    }
    else {
        m = min(m, d) - 1;
        int x = __gcd(d - 1, w);
        w /= x;
        int cnt = m / w;
        if (cnt == 0) {
            cout << 0 << endl;
            return;
        }
        int s = w * ((cnt * (cnt + 1)) / 2);
        ans = cnt * (m + 1) - s;
    }
    cout << ans << endl;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q;
    cin >> q;
    while (q--) {
        solve();
    }
}


#include<bits/stdc++.h>

using namespace std;

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
    return '"' + s + '"';
}

string to_string(const char& s) {
    string res = "'";
    res += s;
    res += "'";
    return res;
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
    string res = "{";
    for (int i = 0; i < static_cast<int>(v.size()); i++) {
        if (i) res += ", ";
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template <size_t N>
string to_string(bitset<N> v) {
    string res = "";
    for (size_t i = 0; i < N; i++) {
        res += static_cast<char>('0' + v[i]);
    }
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
    return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define int long long
#define fi first
#define se second
#define pii pair<int, int>
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define eb emplace_back
#define ld long double

int c(int x) {
    return (x * (x - 1)) / 2;
}

int solve(int m, int d, int w) {
    int ans = 0;
    if (d == 1) {
        ans = 0;
    }
    else if (m != 1) {
        m = min(m, d) - 1;
        int x = __gcd(d - 1, w);
        w /= x;
        int cnt = m / w;
        if (cnt == 0) {
            return 0;
        }
        int s = w * ((cnt * (cnt + 1)) / 2);
        ans = cnt * (m + 1) - s;
    }
    return ans;
}

int X(int m, int d, int w) {
    int ans = 0;
    for (int i = 0; i < m; i++) {
        for (int j = i + 1; j < m; j++) {

        }
    }
    return ans;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q;
    cin >> q;
    while (q--) {
        int m, d, w;
        cin >> m >> d >> w;
        cout << solve(m, d, w) << endl;
    }
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <utility>
#include <deque>
#include <stack>
#include <bitset>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define rep(i,n) for (int i=0;i<n;++i)
#define REP(i,n) for (int i=1;i<=n;++i)
#define all(x) x.begin(),x.end()
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define RI(x) scanf("%d",&x)
#define RII(x,y) scanf("%d%d",&x,&y)
int T;

int main(){
	ios::sync_with_stdio(false);
	cin>>T;
	while(T--){
		int d,m,w;cin>>m>>d>>w;
		int lim=min(d,m);
		if (lim==1){
			cout<<0<<endl;continue;
		}
		int mod=w/__gcd(w,d-1);
		ll ans=0;
		for (int i=0;i<mod;++i){
			ll cnt=(lim-i+mod-1)/mod;
			ans+=cnt*(cnt-1)/2;
		}
		cout<<ans<<endl;
	}

	return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <utility>
#include <deque>
#include <stack>
#include <bitset>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
#define rep(i,n) for (int i=0;i<n;++i)
#define REP(i,n) for (int i=1;i<=n;++i)
#define all(x) x.begin(),x.end()
#define mp make_pair
#define pb push_back
#define pf push_front
#define F first
#define S second
#define RI(x) scanf("%d",&x)
#define RII(x,y) scanf("%d%d",&x,&y)
int T;

int main(){
	ios::sync_with_stdio(false);
	cin>>T;
	while(T--){
		int d,m,w;cin>>m>>d>>w;
		int lim=min(d,m);
		if (lim==1){
			cout<<0<<endl;continue;
		}
		int mod=w/__gcd(w,d-1);
		ll ans=0;
		int rem=(lim-1)%mod;
		ll cnt1=(lim+mod-1)/mod,cnt2=(lim+mod-1)/mod-1;
		ans=cnt1*(cnt1-1)/2*(rem+1)+cnt2*(cnt2-1)/2*(mod-rem-1);

		cout<<ans<<endl;
	}

	return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define endl "\n"

using namespace std;

int main(){
  #ifndef ONLINE_JUDGE
   freopen("input.txt","r",stdin);
   freopen("output.txt","w",stdout);
  #endif
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while(t--){
    ll m,d,w;
    cin >> m >> d >> w;
    // ((x-1)*d + y)%w == ((y-1)*d + x)%w
    // ((y - x)*(d - 1))%w == 0
    // y%w == x%w
    // d - 1 %w == 0
    ll ans = 0;
    if((d - 1)%w == 0){
      ans = m*(m - 1)/2;
    }
    else{
      // 6 7 4
      // 1,3 1,5
      // 2 4 6 8 10
      w /= __gcd(d - 1,w);
      ll cnt = (m)/w;
      ll temp = (m)%w;
      //cout << cnt << " " << temp << endl;
      ans = temp*(cnt + 1)*(cnt)/2 + (w - temp)*cnt*(cnt - 1)/2 ;
    }
    cout << ans << endl;
  }
  return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define endl "\n"

using namespace std;

int main(){
  #ifndef ONLINE_JUDGE
   freopen("input.txt","r",stdin);
   freopen("output.txt","w",stdout);
  #endif
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while(t--){
    ll m,d,w;
    cin >> m >> d >> w;
    // ((x-1)*d + y)%w == ((y-1)*d + x)%w
    // ((y - x)*(d - 1))%w == 0
    // y%w == x%w
    // d - 1 %w == 0
    ll ans = 0;
    if((d - 1)%w == 0){
      ans = m*(m - 1)/2;
    }
    else{
      // 6 7 4
      // 1,3 1,5
      // 2 4 6 8 10
      w /= __gcd(d - 1,w);
      m = min(m,d);
      ll cnt = (m)/w;
      ll temp = (m)%w;
      //cout << cnt << " " << temp << endl;
      ans = temp*(cnt + 1)*(cnt)/2 + (w - temp)*cnt*(cnt - 1)/2 ;
    }
    cout << ans << endl;
  }
  return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define endl "\n"

using namespace std;

int main(){
  #ifndef ONLINE_JUDGE
   freopen("input.txt","r",stdin);
   freopen("output.txt","w",stdout);
  #endif
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while(t--){
    ll m,d,w;
    cin >> m >> d >> w;
    // ((x-1)*d + y)%w == ((y-1)*d + x)%w
    // ((y - x)*(d - 1))%w == 0
    // y%w == x%w
    // d - 1 %w == 0
    ll ans = 0;
    if((d - 1)%w == 0){
      m = min(m,d);
      ans = m*(m - 1)/2;
    }
    else{
      // 6 7 4
      // 1,3 1,5
      // 2 4 6 8 10
      w /= __gcd(d - 1,w);
      m = min(m,d);
      ll cnt = (m)/w;
      ll temp = (m)%w;
      //cout << cnt << " " << temp << endl;
      ans = temp*(cnt + 1)*(cnt)/2 + (w - temp)*cnt*(cnt - 1)/2 ;
    }
    cout << ans << endl;
  }
  return 0;
}


/*
 author : Anubhav Dinesh Patel
 date : 29.07.2020 19:53:53 IST
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL)
#define endl '\n'
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define max_pqueue priority_queue< long long >
#define min_pqueue priority_queue< long long , vector<long long> , greater< long long >>
#define vi vector<int>
#define vii vector<pair<int, int>>
#define vl vector<long long>
#define vll vector<pair<long long, long long>>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define FF first
#define SS second
#define sz(x) (int)x.size()
#define gcase "Case #"<<tcase<<": "
using namespace std;
// using namespace __gnu_pbds;
// typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
// typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
// typedef tree<int, int, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_map;

//~ setbase - cout << setbase (16); cout << 100 << endl; Prints 64
//~ setfill -   cout << setfill ('x') << setw (5); cout << 77 << endl; prints xxx77
//~ setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx
//~ cout.precision(x)  cout<<fixed<<val;  // prints x digits after decimal in val

#ifndef LOCAL_MACHINE
#define cerr if (false) cerr
#endif

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<typename T>
void _printA(T *t, long long sz) { cout<<" { "; for (long long i=0; i<sz; i++) cout<<"["<<i<<"] = "<< t[i]<<endl; cout<<" } \n";}
#ifdef LOCAL_MACHINE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#define debugA(x, y) cerr << "[" << #x << "] = "; _printA(x, y)
#else
#define debug(x...)
#define debugA(x, y)
#endif

const ll _MOD = 998244353LL;

ll mod(ll a, ll m=_MOD) {
	return ((a % m) + m) % m;
}

ll gcd(ll a, ll b) { return __gcd(a, b); }

ll gcd(ll a, ll b, ll & x, ll & y) {
    if (a == 0) {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd(b % a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}

ll modinv(ll a, ll m=_MOD) {
	ll x, y;
	gcd(a, m, x, y);
	x = (x % m + m) % m;
    return x;
}

ll powm(ll a, ll b, ll m=_MOD) {
	if (b == 0) return 1;
	ll ans = powm(a, b/2, m);
	ans = (ans * ans) % m;
	return (b & 1) ? (ans * (a%m)) % m : ans;
}

/* 1. If you can't keep solution in mind, then visualize it on a paper.
 * 2. Try to identify the type of problem - DP, Greedy, Graph, Constructive,
 * 	  Prefix/Suffix, Difference Array, BIT/Segment Tree, etc.
 * 3. Look at the problems from different perspectives - reverse the problem,
 * 	  add instead of delete (maybe?)
 * 4. Divide difficult solutions into cases and/or sequences.
 * 5. Use math rules to solve Nested Summation.
 * 6. Optimisation problems are generally solved with DP, greedy, binary search or brute-force.
 * 7. Try fixing a solution then proving we can't do better or worse than that.
 * ------------------------------------------------------------------
 */

void solve() {
	ll m, d, w;
	cin>>m>>d>>w;
	if ((d-1) % w == 0) {
		debug("here");
		ll x = min(m, d);
		ll ans = (x*x - x)/2;
		cout<<ans<<endl;
		return;
	}
	ll g = gcd(w, (d-1));
	ll k = (w % g == 0) ? w/g : w;
	ll ans = 0;
	ll mul = k;
	while (mul <= min(d, m)) {
		ans += max(0LL, min(d, m) - mul);
		mul += k;
	}
	cout<<ans<<endl;
}

void preprocess() {

}

int main() {
#ifdef LOCAL_MACHINE
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
freopen("in", "r", stdin);
#pragma GCC diagnostic pop
#endif

	fast_io;
	preprocess();
	ll T;
	T = 1;
	cin>>T;
	for (ll t=0; t<T; t++) {
		solve(/* t */);
	}
}


/*
 author : Anubhav Dinesh Patel
 date : 29.07.2020 19:53:53 IST
*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL)
#define endl '\n'
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define max_pqueue priority_queue< long long >
#define min_pqueue priority_queue< long long , vector<long long> , greater< long long >>
#define vi vector<int>
#define vii vector<pair<int, int>>
#define vl vector<long long>
#define vll vector<pair<long long, long long>>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define FF first
#define SS second
#define sz(x) (int)x.size()
#define gcase "Case #"<<tcase<<": "
using namespace std;
// using namespace __gnu_pbds;
// typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
// typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
// typedef tree<int, int, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_map;

//~ setbase - cout << setbase (16); cout << 100 << endl; Prints 64
//~ setfill -   cout << setfill ('x') << setw (5); cout << 77 << endl; prints xxx77
//~ setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx
//~ cout.precision(x)  cout<<fixed<<val;  // prints x digits after decimal in val

#ifndef LOCAL_MACHINE
#define cerr if (false) cerr
#endif

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
template<typename T>
void _printA(T *t, long long sz) { cout<<" { "; for (long long i=0; i<sz; i++) cout<<"["<<i<<"] = "<< t[i]<<endl; cout<<" } \n";}
#ifdef LOCAL_MACHINE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#define debugA(x, y) cerr << "[" << #x << "] = "; _printA(x, y)
#else
#define debug(x...)
#define debugA(x, y)
#endif

const ll _MOD = 998244353LL;

ll mod(ll a, ll m=_MOD) {
	return ((a % m) + m) % m;
}

ll gcd(ll a, ll b) { return __gcd(a, b); }

ll gcd(ll a, ll b, ll & x, ll & y) {
    if (a == 0) {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd(b % a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}

ll modinv(ll a, ll m=_MOD) {
	ll x, y;
	gcd(a, m, x, y);
	x = (x % m + m) % m;
    return x;
}

ll powm(ll a, ll b, ll m=_MOD) {
	if (b == 0) return 1;
	ll ans = powm(a, b/2, m);
	ans = (ans * ans) % m;
	return (b & 1) ? (ans * (a%m)) % m : ans;
}

/* 1. If you can't keep solution in mind, then visualize it on a paper.
 * 2. Try to identify the type of problem - DP, Greedy, Graph, Constructive,
 * 	  Prefix/Suffix, Difference Array, BIT/Segment Tree, etc.
 * 3. Look at the problems from different perspectives - reverse the problem,
 * 	  add instead of delete (maybe?)
 * 4. Divide difficult solutions into cases and/or sequences.
 * 5. Use math rules to solve Nested Summation.
 * 6. Optimisation problems are generally solved with DP, greedy, binary search or brute-force.
 * 7. Try fixing a solution then proving we can't do better or worse than that.
 * ------------------------------------------------------------------
 */

void solve() {
	ll m, d, w;
	cin>>m>>d>>w;
	if ((d-1) % w == 0) {
		debug("here");
		ll x = min(m, d);
		ll ans = (x*x - x)/2;
		cout<<ans<<endl;
		return;
	}
	ll g = gcd(w, (d-1));
	ll k = (w % g == 0) ? w/g : w;
	ll ans = 0;
	ll mul = min(d,m) / k;
	ans = mul*min(d, m) - (mul*(mul+1))/2 * k;
	cout<<ans<<endl;
}

void preprocess() {

}

int main() {
#ifdef LOCAL_MACHINE
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
freopen("in", "r", stdin);
#pragma GCC diagnostic pop
#endif

	fast_io;
	preprocess();
	ll T;
	T = 1;
	cin>>T;
	for (ll t=0; t<T; t++) {
		solve(/* t */);
	}
}


#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortbysecdesc(const pair<int,int> &a,
                   const pair<int,int> &b)
{
       return a.second>b.second;
}

/*
Mistakes

- while using pairs make sure you comparator datatype it's int by default change it as per the need
- Modify comparator if you want to
*/
#define f first
#define s second
#define ll long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll64 int64_t
#define pb push_back
#define pll pair<long long int,long long int>
#define pi pair<int,int>
#define mi map<int,int>
#define mll map<long long int,long long int>
#define umi unordered_map<int,int>
#define umll unordered_map<long long int,long long int>
#define vpi vector<pair<int,int>>
#define vpll vector<pair<long long int,long long int>>
#define mod 1000000007
#define fp(i,x,n) for(int i=x;i<n;i++)
#define fn(i,x,n) for(int i=x;i>n;i--)
#define fpm(i,m) for(auto i=m.begin();i!=m.end();i++)
#define asort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysec)
#define asort_vp_first(vect) sort(vect.begin(), vect.end())
#define dsort_vp_first(vect) sort(vect.begin(), vect.end(), sortinrev)
#define dsort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysecdesc)
#define vi vector<int>
#define vll vector<long long int>
#define c(x) cout<<x<<endl;
#define M 1000000007
ll power(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
        ans*=a;
        a*=a;
        b/=2;
    }
    return ans;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll m,d,w;
        cin>>m>>d>>w;

        /*
        Total days = d*m
        For day to be on same weed day is a - b = k*w Or a=b(mod w)
        for ambiquous day yth month x day = xth month y day => (y-1)*d + x = ((x-1)*d + y)(mod w)
        furthur improvment = y(d-1)=x(d-1) ... (x-y)*(d-1) = 0 (or multiple of w) OR (x-y)*(d-1) = kw
        divide by gcd(d-1,w) => (x-y) * r = k'w' (where r = (d-1)/(gcd(d-1,w)) and w' = w/(gcd(w,d-1)))
        (x-y) = k'w' OR x=y(mod w')

        {x,y} in [1,min(d,m)] // ambiquous pair range
        Total = w'*(kC2) + r*w'
        */

        d--;
        w = w / __gcd(d,w);
        ll r = min(d+1,m); // Max from range

        ll k = r/w;
        ll p = r%w;
        ll ans = w*k*(k-1)/2 + p*k;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortbysecdesc(const pair<int,int> &a,
                   const pair<int,int> &b)
{
       return a.second>b.second;
}

/*
Mistakes

- while using pairs make sure you comparator datatype it's int by default change it as per the need
- Modify comparator if you want to
*/
#define f first
#define s second
#define ll long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll64 int64_t
#define pb push_back
#define pll pair<long long int,long long int>
#define pi pair<int,int>
#define mi map<int,int>
#define mll map<long long int,long long int>
#define umi unordered_map<int,int>
#define umll unordered_map<long long int,long long int>
#define vpi vector<pair<int,int>>
#define vpll vector<pair<long long int,long long int>>
#define mod 1000000007
#define fp(i,x,n) for(int i=x;i<n;i++)
#define fn(i,x,n) for(int i=x;i>n;i--)
#define fpm(i,m) for(auto i=m.begin();i!=m.end();i++)
#define asort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysec)
#define asort_vp_first(vect) sort(vect.begin(), vect.end())
#define dsort_vp_first(vect) sort(vect.begin(), vect.end(), sortinrev)
#define dsort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysecdesc)
#define vi vector<int>
#define vll vector<long long int>
#define c(x) cout<<x<<endl;
#define M 1000000007
ll power(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
        ans*=a;
        a*=a;
        b/=2;
    }
    return ans;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll m,d,w;
        cin>>m>>d>>w;

        /*
        Total days = d*m
        For day to be on same weed day is a - b = k*w Or a=b(mod w)
        for ambiquous day yth month x day = xth month y day => (y-1)*d + x = ((x-1)*d + y)(mod w)
        furthur improvment = y(d-1)=x(d-1) ... (x-y)*(d-1) = 0 (or multiple of w) OR (x-y)*(d-1) = kw
        divide by gcd(d-1,w) => (x-y) * r = k'w' (where r = (d-1)/(gcd(d-1,w)) and w' = w/(gcd(w,d-1)))
        (x-y) = k'w' OR x=y(mod w')

        {x,y} in [1,min(d,m)] // ambiquous pair range
        Total = w'*(kC2) + r*w'
        */

        d--;
        w = w / __gcd(d,w);
        ll r = min(d,m); // Max from range

        ll k = r/w;
        ll p = r%w;
        ll ans = w*k*(k-1)/2 + p*k;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortbysecdesc(const pair<int,int> &a,
                   const pair<int,int> &b)
{
       return a.second>b.second;
}

/*
Mistakes

- while using pairs make sure you comparator datatype it's int by default change it as per the need
- Modify comparator if you want to
*/
#define f first
#define s second
#define ll long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll64 int64_t
#define pb push_back
#define pll pair<long long int,long long int>
#define pi pair<int,int>
#define mi map<int,int>
#define mll map<long long int,long long int>
#define umi unordered_map<int,int>
#define umll unordered_map<long long int,long long int>
#define vpi vector<pair<int,int>>
#define vpll vector<pair<long long int,long long int>>
#define mod 1000000007
#define fp(i,x,n) for(int i=x;i<n;i++)
#define fn(i,x,n) for(int i=x;i>n;i--)
#define fpm(i,m) for(auto i=m.begin();i!=m.end();i++)
#define asort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysec)
#define asort_vp_first(vect) sort(vect.begin(), vect.end())
#define dsort_vp_first(vect) sort(vect.begin(), vect.end(), sortinrev)
#define dsort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysecdesc)
#define vi vector<int>
#define vll vector<long long int>
#define c(x) cout<<x<<endl;
#define M 1000000007
ll power(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
        ans*=a;
        a*=a;
        b/=2;
    }
    return ans;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll m,d,w;
        cin>>m>>d>>w;

        /*
        Total days = d*m
        For day to be on same weed day is a - b = k*w Or a=b(mod w)
        for ambiquous day yth month x day = xth month y day => (y-1)*d + x = ((x-1)*d + y)(mod w)
        furthur improvment = y(d-1)=x(d-1) ... (x-y)*(d-1) = 0 (or multiple of w) OR (x-y)*(d-1) = kw
        divide by gcd(d-1,w) => (x-y) * r = k'w' (where r = (d-1)/(gcd(d-1,w)) and w' = w/(gcd(w,d-1)))
        (x-y) = k'w' OR x=y(mod w')

        {x,y} in [1,min(d,m)] // ambiquous pair range
        Total = w'*(kC2) + r*w'
        */

        d--;
        w = w / __gcd(d,w);
        ll r = min(d+1,m); // Max from range (d+1) because we have decremented once

        ll k = r/w;
        ll p = r%w;
        ll ans = w*k*(k-1)/2 + p*k;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortbysecdesc(const pair<int,int> &a,
                   const pair<int,int> &b)
{
       return a.second>b.second;
}

/*
Mistakes

- while using pairs make sure you comparator datatype it's int by default change it as per the need
- Modify comparator if you want to
*/
#define f first
#define s second
#define ll long long int
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll64 int64_t
#define pb push_back
#define pll pair<long long int,long long int>
#define pi pair<int,int>
#define mi map<int,int>
#define mll map<long long int,long long int>
#define umi unordered_map<int,int>
#define umll unordered_map<long long int,long long int>
#define vpi vector<pair<int,int>>
#define vpll vector<pair<long long int,long long int>>
#define mod 1000000007
#define fp(i,x,n) for(int i=x;i<n;i++)
#define fn(i,x,n) for(int i=x;i>n;i--)
#define fpm(i,m) for(auto i=m.begin();i!=m.end();i++)
#define asort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysec)
#define asort_vp_first(vect) sort(vect.begin(), vect.end())
#define dsort_vp_first(vect) sort(vect.begin(), vect.end(), sortinrev)
#define dsort_vp_second(vect) sort(vect.begin(), vect.end(), sortbysecdesc)
#define vi vector<int>
#define vll vector<long long int>
#define c(x) cout<<x<<endl;
#define M 1000000007
ll power(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
        ans*=a;
        a*=a;
        b/=2;
    }
    return ans;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll m,d,w;
        cin>>m>>d>>w;

        /*
        Total days = d*m
        For day to be on same weed day is a - b = k*w Or a=b(mod w)
        for ambiquous day yth month x day = xth month y day => (y-1)*d + x = ((x-1)*d + y)(mod w)
        furthur improvment = y(d-1)=x(d-1) ... (x-y)*(d-1) = 0 (or multiple of w) OR (x-y)*(d-1) = kw
        divide by gcd(d-1,w) => (x-y) * r = k'w' (where r = (d-1)/(gcd(d-1,w)) and w' = w/(gcd(w,d-1)))
        (x-y) = k'w' OR x=y(mod w')

        {x,y} in [1,min(d,m)] // ambiquous pair range
        Total = w'*(kC2) + r*w'
        */

        if(d==1){
        cout<<0<<endl;}

        d--;
        w = w / __gcd(d,w);
        ll r = min(d+1,m); // Max from range

        ll k = r/w;
        ll p = r%w;
        ll ans = w*k*(k-1)/2 + p*k;
        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>

using namespace std;
#define ub upper_bound
#define lb lower_bound
#define bs binary_search
#define mp make_pair
#define eb emplace_back
#define pb push_back
#define endl "\n"
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define ff first
#define ss second
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);
#define w(t) while(t--)
#define fr(i,n) for(ll i=0;i<n;i++)
#define f(i,a,n) for(ll i=a;i<n;i++)
#define all(x) x.begin(),x.end()
#define input(arr,n) for(ll i1=0;i1<n;i1++ )cin>>arr[i1]

typedef long long int ll;
typedef unsigned long long ull;
typedef double db;
typedef vector<int> vl;
typedef vector<ll> v;
typedef set<ll> st;
#define PI 3.14159265
typedef pair<ll,ll> pll;

int main() {
	IOS
    ll t;
    ll c,r,m,n,a,b,i,j,k,d,w,z;

    cin>>t;
    w(t)
    {
    ll sum=0,maxi=INT_MIN, mini=INT_MAX,count=0,flag=0,small,big,ans,diff;

    cin>>m>>d>>w;
    if(d==1){
        cout<<"0"<<endl;
    }
    else{
        w/=__gcd(d,w);
        z=min(d,m);
        k=r/w;
        r=z%w;
        ans=(w*k*(k-1)/2)+(k*r);
        cout<<ans<<endl;
    }

    }
	return 0;
}


#include <bits/stdc++.h>

using namespace std;
#define ub upper_bound
#define lb lower_bound
#define bs binary_search
#define mp make_pair
#define eb emplace_back
#define pb push_back
#define endl "\n"
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define ff first
#define ss second
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);
#define w(t) while(t--)
#define fr(i,n) for(ll i=0;i<n;i++)
#define f(i,a,n) for(ll i=a;i<n;i++)
#define all(x) x.begin(),x.end()
#define input(arr,n) for(ll i1=0;i1<n;i1++ )cin>>arr[i1]

typedef long long int ll;
typedef unsigned long long ull;
typedef double db;
typedef vector<int> vl;
typedef vector<ll> v;
typedef set<ll> st;
#define PI 3.14159265
typedef pair<ll,ll> pll;

int main() {
	IOS
    ll t;
    ll c,r,m,n,a,b,i,j,k,d,w,z;

    cin>>t;
    w(t)
    {
    ll sum=0,maxi=INT_MIN, mini=INT_MAX,count=0,flag=0,small,big,ans,diff;

    cin>>m>>d>>w;
    if(d==1){
        cout<<"0"<<endl;
    }
    else{

	w /= __gcd(d-1,w);

    z = min(d,m);

    k = z / w;
	r = z % w;
	ans = w*k*(k-1)/2 + r*k;
	cout<<ans<<endl;
    }

    }
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define pb push_back
#define mp make_pair
#define F first
#define S second
const ll bg = 1000000007;
#define ff(i,n) for(i=0;i<n;i++)
#define vv vector<vector<ll> >
vector<vector<ll> >master [31];
vv mul(vv a,vv b)
{
    vv f;
    ll i,j,k,n1 = a.size(),n2 = a[0].size(),m1 = b.size(),m2 = b[0].size();
    ff(i,n1)
    {
        vector<ll> temp;
    	ff(j,m2)
         	temp.pb(0);
      	f.pb(temp);
     }
    ff(i,n1)
       ff(j,m2)
           ff(k,n2)
              f[i][j] = (f[i][j] + (a[i][k]*b[k][j]))%bg;
    return f;
}
vv power(vv x,ll y,ll bin)
{
	if(y==1)
	{
	    master[bin] = x;
	    return x;
	}
	vv d = power(x,y/2,bin-1);
	d = mul(d,d);
	master[bin] = d;
	return d;
}
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
	return d;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		if(d==1)
		{
			ans = (f*(f-1))/2;
			cout<<ans<<endl;
		}
		else
		{
			ll mul = (w/(gcd(w,d-1)));
			ll s = (f+1)/mul;
			if((f+1)%mul==0)
			{
				ans = mul*nc2(s);
			}
			else
			{
				ll a = (f+1)%mul,b = (f+1)-a;
				ans = a*nc2(s+1) + b*nc2(s);
			}
			cout<<ans<<endl;
		}
	}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
	return d;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		cout<<((f+1)%(w/(gcd(w,d-1)))==0)*((w/(gcd(w,d-1)))*nc2((f+1)/mul)) + (1-(((f+1)%(w/(gcd(w,d-1)))==0)))*(((f+1)%(w/(gcd(w,d-1))))*nc2((f+1)/mul+1) + ((w/(gcd(w,d-1)))-((f+1)%(w/(gcd(w,d-1)))))*nc2((f+1)/mul))<<endl;
	}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define pb push_back
#define mp make_pair
#define F first
#define S second
const ll bg = 1000000007;
#define ff(i,n) for(i=0;i<n;i++)
#define vv vector<vector<ll> >
vector<vector<ll> >master [31];
vv mul(vv a,vv b)
{
    vv f;
    ll i,j,k,n1 = a.size(),n2 = a[0].size(),m1 = b.size(),m2 = b[0].size();
    ff(i,n1)
    {
        vector<ll> temp;
    	ff(j,m2)
         	temp.pb(0);
      	f.pb(temp);
     }
    ff(i,n1)
       ff(j,m2)
           ff(k,n2)
              f[i][j] = (f[i][j] + (a[i][k]*b[k][j]))%bg;
    return f;
}
vv power(vv x,ll y,ll bin)
{
	if(y==1)
	{
	    master[bin] = x;
	    return x;
	}
	vv d = power(x,y/2,bin-1);
	d = mul(d,d);
	master[bin] = d;
	return d;
}
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		if(d==1)
		{
			ans = (f*(f-1))/2;
			cout<<ans<<endl;
		}
		else
		{
			ll mul = (w/(gcd(w,d-1)));
			ll s = (f+1)/mul;
			if((f+1)%mul==0)
			{
				ans = mul*nc2(s);
			}
			else
			{
				ll a = (f+1)%mul,b = (f+1)-a;
				ans = a*nc2(s+1) + b*nc2(s);
			}
			cout<<ans<<endl;
		}
	}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
	return d;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		if(d==1)
		         cout<<nc2(f)<<endl;
		else
		{
			ll mul = (w/(gcd(w,d-1)));
			ll s = (f+1)/mul;
			cout<<((f+1)%mul==0)*(mul*nc2(s)) + (1-(((f+1)%mul==0)))*(((f+1)%mul)*nc2(s+1) + (mul-((f+1)%mul))*nc2(s))<<endl;
		}
	}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define pb push_back
#define mp make_pair
#define F first
#define S second
const ll bg = 1000000007;
#define ff(i,n) for(i=0;i<n;i++)
#define vv vector<vector<ll> >
vector<vector<ll> >master [31];
vv mul(vv a,vv b)
{
    vv f;
    ll i,j,k,n1 = a.size(),n2 = a[0].size(),m1 = b.size(),m2 = b[0].size();
    ff(i,n1)
    {
        vector<ll> temp;
    	ff(j,m2)
         	temp.pb(0);
      	f.pb(temp);
     }
    ff(i,n1)
       ff(j,m2)
           ff(k,n2)
              f[i][j] = (f[i][j] + (a[i][k]*b[k][j]))%bg;
    return f;
}
vv power(vv x,ll y,ll bin)
{
	if(y==1)
	{
	    master[bin] = x;
	    return x;
	}
	vv d = power(x,y/2,bin-1);
	d = mul(d,d);
	master[bin] = d;
	return d;
}
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
	return d;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		if(d==1)
		{
			ans = (f*(f-1))/2;
			cout<<ans<<endl;
		}
		else
		{
			ll mul = (w/(gcd(w,d-1)));
			ll s = (f+1)/mul;
			if((f+1)%mul==0)
			{
				ans = mul*nc2(s);
			}
			else
			{
				ll a = (f+1)%mul,b = mul-a;
				ans = a*nc2(s+1) + b*nc2(s);
			}
			cout<<ans<<endl;
		}
	}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll gcd(ll a,ll b)
{
	if(b==0)
		return a;
	else
	    return gcd(b,a%b);
}
ll nc2(ll f)
{
	ll d = (f*(f-1))/2;
	return d;
}
int main()
{

	ll t;
	cin>>t;
	while(t--)
	{
		ll m,d,w,ans;
		cin>>m>>d>>w;
		ll f = min(m,d)-1;
		if(0)
		         cout<<nc2(f)<<endl;
		else
		{
			ll mul = (w/(gcd(w,d-1)));
			ll s = (f+1)/mul;
			cout<<((f+1)%mul==0)*(mul*nc2(s)) + (1-(((f+1)%mul==0)))*(((f+1)%mul)*nc2(s+1) + (mul-((f+1)%mul))*nc2(s))<<endl;
		}
	}
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define w(t) int t;cin>>t;while(t--)

ll _gcd(ll x,ll y)
{
    if(y==0)return x;
    else _gcd(y,x%y);
}

int main(){
    w(t){
        ll m,d,w;
        cin>>m>>d>>w;
        ll lim=min(m,d);
        if(d==1){
        ll ans=m*(m-1)/2;
        cout<<ans<<endl;
        continue;
        }
        d--;
        w/=_gcd(d,w);
        ll k=lim/w;
        ll r=lim%w;
        ll ans=(w*k*(k-1)/2) +(r*k);
        cout<<ans<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define w(t) int t;cin>>t;while(t--)

ll _gcd(ll x,ll y)
{
    if(y==0)return x;
    else return _gcd(y,x%y);
}

int main(){
    w(t){
        ll m,d,w;
        cin>>m>>d>>w;
        ll lim=min(m,d);
        if(d==1){
        ll ans=0;
        cout<<ans<<endl;
        continue;
        }
        d--;
        w/=_gcd(d,w);
        ll k=lim/w;
        ll r=lim%w;
        ll ans=(w*k*(k-1)/2) +(r*k);
        cout<<ans<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define w(t) int t;cin>>t;while(t--)

ll _gcd(ll x,ll y)
{
    if(y==0)return x;
    else _gcd(y,x%y);
}

int main(){
    w(t){
        ll m,d,w;
        cin>>m>>d>>w;
        ll lim=min(m,d);
        if(d==1){
        ll ans=0;
        cout<<ans<<endl;
        continue;
        }
        d--;
        w/=_gcd(d,w);
        ll k=lim/w;
        ll r=lim%w;
        ll ans=(w*k*(k-1)/2) +(r*k);
        cout<<ans<<endl;
    }
    return 0;
}


#include <algorithm>
#include <cstdio>
using namespace std;

int t, n, d, w;

int _gcd(int a, int b) { return b ? _gcd(b, a % b) : a; }

int main(int argc, char *argv[]) {
    open();

    scanf("%d", &t);
    while (t--) {
        scanf("%d %d %d", &n, &d, &w);
        int k = min(n, d);
        if ((d - 1) % w == 0) printf("%lld\n", 1LL * k * (k - 1) / 2);
        else {
            w /= _gcd(d - 1, w);
            int q = k / w;
            printf("%lld\n", q * (2 * k - 1LL * (q + 1) * w) / 2);
        }
    }
    return 0;
}


#include <algorithm>
#include <cstdio>
using namespace std;

int t, n, d, w;

int _gcd(int a, int b) { return b ? _gcd(b, a % b) : a; }

int main(int argc, char *argv[]) {
    scanf("%d", &t);
    while (t--) {
        scanf("%d %d %d", &n, &d, &w);
        int k = min(n, d);
        if ((d - 1) % w == 0) printf("%lld\n", 1LL * k * (k - 1) / 2);
        else {
            w /= _gcd(d - 1, w);
            int q = k / w;
            printf("%lld\n", q * (2 * k - 1LL * (q + 1) * w) / 2);
        }
    }
    return 0;
}


#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#define X first
#define Y second

#ifdef NON_SUBMIT
#define TEST(n) (n)
#else
#define TEST(n) ((void)0)
#endif

#pragma warning(disable:4996)
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair <ll, int> pli;
typedef pair <int, pii> piii;
typedef tuple <int, int, int> ti3;

clock_t start_time, end_time;

void open() {
    TEST(freopen("input.txt", "r", stdin));
    TEST(freopen("output.txt", "w", stdout));
    TEST(freopen("debug.txt", "w", stderr));
    TEST(start_time = clock());
}

void close() {
    TEST(end_time = clock());
    TEST(printf("Total time : %Lf seconds\n", (long double)(end_time - start_time) / CLOCKS_PER_SEC));
}

const int MAX = 1e5 + 1;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3fLL;
const db PI = acos(-1);
const ldb ERR = 1e-10;
const int move_r[] = {-1, 0, 1, 0, -1, -1, 1, 1};
const int move_c[] = {0, -1, 0, 1, -1, 1, -1, 1};

int t, n, d, w;

int _gcd(int a, int b) { return b ? _gcd(b, a % b) : a; }

int main(int argc, char *argv[]) {
    open();

    scanf("%d", &t);
    while (t--) {
        scanf("%d %d %d", &n, &d, &w);
        int k = min(n, d);
        if ((d - 1) % w == 0) printf("%lld\n", 1LL * k * (k - 1) / 2);
        else {
            w /= _gcd(d - 1, w);
            int q = k / w;
            printf("%lld\n", q * (2 * k - 1LL * (q + 1) * w) / 2);
        }
    }

    close();
    return 0;
}


#include<bits/stdc++.h>
#include<queue>
using namespace std;

#define what_is(x) cerr << #x << " is " << x << endl;
#define PI acos(-1)
#define hell 1000000007
#define HELL 998244353
#define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define fix(n) cout << fixed << setprecision(n)
#define mset(a,n) memset(a,n,sizeof a)
#define rep(i,a,b) for (__typeof((b)) i=(a);i<(b);i++)
#define repp(i,a,b,p) for(__typeof((b)) i=(a);i<(b);i+=p)
#define ren(i,a,b) for(__typeof((a)) i=(a);i>=(b);i--)
#define renn(i,a,b,p) for(__typeof((a) i=(a);i>=(b);i-=p)
#define ADD(a,b,c) ((a)%c+(b)%c)%c
#define SUB(a,b,c) ((a)%c-(b)%c+c)%c
#define MUL(a,b,c) (((a)%c)*((b)%c))%c
#define lbd lower_bound
#define ubd upper_bound
#define ll long long
#define ld long double
#define pb push_back
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define all(v) (v).begin(), (v).end()
#define sz(x) (ll)x.size()
// #define out(n) cout<<n<<" "
#define outl(n) cout<<n<<endl
#define bug(n) {outl(n);return;}
#define pii pair<int,int>
#define lim 9223372036854775805
#define ninf -9223372036854775802
#define M 1000000007
#define eps 1e-9
#define MAX 10
#define N 100001
#define db(a) for(auto it:a) {cout<<it<<" ";}cout<<endl;
ll prime[MAX];
ll fact[MAX];

const long long INF64 = 1e18;
ll vpow(ll a,ll b,ll p){
    if(b==0)
        return 1;
    if(b==1)
            return a;
    ll temp=vpow(a,b/2,p);
    temp*=temp;
    temp%=p;
    if(b%2==0)
        return temp;
    temp=temp*a;
    temp%=p;
    return temp;
}

ll gcd(ll a,ll b){
     if(a==0)
         return b;
     return gcd(b%a,a);
 }

ll inverseMod(ll a,ll b,ll p){
    if(b==0)
        return 1;
    ll temp=vpow(b,p-2,p);
    ll ans=temp*a;
    ans%=p;
    return ans;
}
void sieve()
{
    prime[0] = prime[1] = 1;
    for (ll i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            for (int j = i * 2; j < MAX; j += i) {
                if (prime[j] == 0) {
                    prime[j] = i;
                }
            }
            prime[i] = i;
        }
    }
}

void factorial(){
    fact[0]=1;
    fact[1]=1;
    rep(i,2,MAX){
        fact[i]=(fact[i-1]*i);
        // fact[i]%=M;
    }
}
ll rand(ll a,ll b){
    return a+rand()%(b-a+1);
}

void solve(ll ttt){
    ll m,d,w;
    cin>>m>>d>>w;
    ll ans=0;
    if(d==1){
        cout<<0<<endl;
        return ;
    }
    ll g=gcd(w,d-1);
    ll rem=w/g;
    ll t=min(d,m)-1;
    ll ind=t/rem;
    ans+=((ind*(ind-1))/2)*rem;
    // ans=((t*(t+1))/2)/rem;
    rep(i,ind*rem,(ll)min(d,m)){
        ans+=i/rem;
    }
    cout<<ans<<endl;
}
int main(){
    io;
    // sieve();
    // factorial();
#ifndef ONLINE_JUDGE
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
#endif
    ll t=1;
    cin>>t;
    fix(12);
    rep(q,1,t+1){
        // cout<<"Case #"<<q<<": ";
         solve(q);
        //solve2();
    }
    return 0;

}


#include<bits/stdc++.h>
#include<queue>
using namespace std;

#define what_is(x) cerr << #x << " is " << x << endl;
#define PI acos(-1)
#define hell 1000000007
#define HELL 998244353
#define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define fix(n) cout << fixed << setprecision(n)
#define mset(a,n) memset(a,n,sizeof a)
#define rep(i,a,b) for (__typeof((b)) i=(a);i<(b);i++)
#define repp(i,a,b,p) for(__typeof((b)) i=(a);i<(b);i+=p)
#define ren(i,a,b) for(__typeof((a)) i=(a);i>=(b);i--)
#define renn(i,a,b,p) for(__typeof((a) i=(a);i>=(b);i-=p)
#define ADD(a,b,c) ((a)%c+(b)%c)%c
#define SUB(a,b,c) ((a)%c-(b)%c+c)%c
#define MUL(a,b,c) (((a)%c)*((b)%c))%c
#define lbd lower_bound
#define ubd upper_bound
#define ll long long
#define ld long double
#define pb push_back
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define all(v) (v).begin(), (v).end()
#define sz(x) (ll)x.size()
// #define out(n) cout<<n<<" "
#define outl(n) cout<<n<<endl
#define bug(n) {outl(n);return;}
#define pii pair<int,int>
#define lim 9223372036854775805
#define ninf -9223372036854775802
#define M 1000000007
#define eps 1e-9
#define MAX 10
#define N 100001
#define db(a) for(auto it:a) {cout<<it<<" ";}cout<<endl;
ll prime[MAX];
ll fact[MAX];

const long long INF64 = 1e18;
ll vpow(ll a,ll b,ll p){
    if(b==0)
        return 1;
    if(b==1)
            return a;
    ll temp=vpow(a,b/2,p);
    temp*=temp;
    temp%=p;
    if(b%2==0)
        return temp;
    temp=temp*a;
    temp%=p;
    return temp;
}

ll gcd(ll a,ll b){
     if(a==0)
         return b;
     return gcd(b%a,a);
 }

ll inverseMod(ll a,ll b,ll p){
    if(b==0)
        return 1;
    ll temp=vpow(b,p-2,p);
    ll ans=temp*a;
    ans%=p;
    return ans;
}
void sieve()
{
    prime[0] = prime[1] = 1;
    for (ll i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            for (int j = i * 2; j < MAX; j += i) {
                if (prime[j] == 0) {
                    prime[j] = i;
                }
            }
            prime[i] = i;
        }
    }
}

void factorial(){
    fact[0]=1;
    fact[1]=1;
    rep(i,2,MAX){
        fact[i]=(fact[i-1]*i);
        // fact[i]%=M;
    }
}
ll rand(ll a,ll b){
    return a+rand()%(b-a+1);
}

void solve(ll ttt){
    ll m,d,w;
    cin>>m>>d>>w;
    ll ans=0;
    if(d==1){
        cout<<0<<endl;
        return ;
    }
    ll g=gcd(w,d-1);
    ll rem=w/g;
    ll t=min(d,m)-1;
    ll ind=t/rem;
    ans+=((ind*(ind-1))/2)*rem;
    ans+=(ind)*(min(d,m)-(ind*rem));
    // ans=((t*(t+1))/2)/rem;
    // rep(i,ind*rem,(ll)min(d,m)){
    //     ans+=i/rem;
    // }
    cout<<ans<<endl;
}
int main(){
    io;
    // sieve();
    // factorial();
#ifndef ONLINE_JUDGE
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
#endif
    ll t=1;
    cin>>t;
    fix(12);
    rep(q,1,t+1){
        // cout<<"Case #"<<q<<": ";
         solve(q);
        //solve2();
    }
    return 0;

}


#include<bits/stdc++.h>
#include<queue>
using namespace std;

#define what_is(x) cerr << #x << " is " << x << endl;
#define PI acos(-1)
#define hell 1000000007
#define HELL 998244353
#define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define fix(n) cout << fixed << setprecision(n)
#define mset(a,n) memset(a,n,sizeof a)
#define rep(i,a,b) for (__typeof((b)) i=(a);i<(b);i++)
#define repp(i,a,b,p) for(__typeof((b)) i=(a);i<(b);i+=p)
#define ren(i,a,b) for(__typeof((a)) i=(a);i>=(b);i--)
#define renn(i,a,b,p) for(__typeof((a) i=(a);i>=(b);i-=p)
#define ADD(a,b,c) ((a)%c+(b)%c)%c
#define SUB(a,b,c) ((a)%c-(b)%c+c)%c
#define MUL(a,b,c) (((a)%c)*((b)%c))%c
#define lbd lower_bound
#define ubd upper_bound
#define ll long long
#define ld long double
#define pb push_back
#define fi first
#define se second
#define vll vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define all(v) (v).begin(), (v).end()
#define sz(x) (ll)x.size()
// #define out(n) cout<<n<<" "
#define outl(n) cout<<n<<endl
#define bug(n) {outl(n);return;}
#define pii pair<int,int>
#define lim 9223372036854775805
#define ninf -9223372036854775802
#define M 1000000007
#define eps 1e-9
#define MAX 10
#define N 100001
#define db(a) for(auto it:a) {cout<<it<<" ";}cout<<endl;
ll prime[MAX];
ll fact[MAX];

const long long INF64 = 1e18;
ll vpow(ll a,ll b,ll p){
    if(b==0)
        return 1;
    if(b==1)
            return a;
    ll temp=vpow(a,b/2,p);
    temp*=temp;
    temp%=p;
    if(b%2==0)
        return temp;
    temp=temp*a;
    temp%=p;
    return temp;
}

ll gcd(ll a,ll b){
     if(a==0)
         return b;
     return gcd(b%a,a);
 }

ll inverseMod(ll a,ll b,ll p){
    if(b==0)
        return 1;
    ll temp=vpow(b,p-2,p);
    ll ans=temp*a;
    ans%=p;
    return ans;
}
void sieve()
{
    prime[0] = prime[1] = 1;
    for (ll i = 2; i < MAX; i++) {
        if (prime[i] == 0) {
            for (int j = i * 2; j < MAX; j += i) {
                if (prime[j] == 0) {
                    prime[j] = i;
                }
            }
            prime[i] = i;
        }
    }
}

void factorial(){
    fact[0]=1;
    fact[1]=1;
    rep(i,2,MAX){
        fact[i]=(fact[i-1]*i);
        // fact[i]%=M;
    }
}
ll rand(ll a,ll b){
    return a+rand()%(b-a+1);
}

void solve(ll ttt){
    ll m,d,w;
    cin>>m>>d>>w;
    ll ans=0;
    if(d==1){
        cout<<0<<endl;
        return ;
    }
    ll g=gcd(w,d-1);
    ll rem=w/g;
    ll t=min(d,m)-1;
    ll ind=t/rem;
    ans+=((ind*(ind-1))/2)*rem;
    ans+=(ind)*(t-(ind*rem));
    // ans=((t*(t+1))/2)/rem;
    // rep(i,ind*rem,(ll)min(d,m)){
        // ans+=i/rem;
    // }
    cout<<ans<<endl;
}
int main(){
    io;
    // sieve();
    // factorial();
#ifndef ONLINE_JUDGE
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
#endif
    ll t=1;
    cin>>t;
    fix(12);
    rep(q,1,t+1){
        // cout<<"Case #"<<q<<": ";
         solve(q);
        //solve2();
    }
    return 0;

}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define pb                push_back
#define ppb               pop_back
#define pf                push_front
#define ppf               pop_front
#define all(x)            (x).begin(),(x).end()
#define int               long long
#define fr                first
#define sc                second
#define vc                vector
#define endl              '\n'
#define pii               pair<int,int>
#define msi               map<string,int>
#define mii               map<int,int>
#define psi               pair<string,int>
#define pis               pair<int,string>
#define mem1(a)           memset(a,-1,sizeof(a))
#define mem0(a)           memset(a,0,sizeof(a))
#define rep(i,a,b)        for(int i=a;i<b;i++)
#define LSB(i)            ((i)&-(i))

template<typename T>
using oset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

int n,m;

void solve()
{
freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
cin>>n>>m;
int trees[n][m];
memset(trees,0,sizeof(trees));
int k;cin>>k;
            for(int i=0;i<k;i++)
                {
                  int c,r;
                  cin>>c>>r;
                  c--,r--;
                  trees[r][c]=1;
                }
int d[n][m];
for(int i=0;i<n;i++)
    {
      for(int j=0;j<m;j++)
          {
            d[i][j]=INT_MAX;
            if(trees[i][j]==1)
              d[i][j]=0;
          }
    }
for(int i=0;i<n;i++)
      {
        for(int j=0;j<m;j++)
           {
            if(trees[i][j]==0) continue;
             else
                {
                   for(int l=0;l<n;l++)
                     for(int k=0;k<m;k++)
                        {
                          d[l][k]=min(d[l][k],abs(i-l)+abs(k-j));
                        }
                }
           }
      }
int maxi=INT_MIN;
for(int i=0;i<n;i++)
  for(int j=0;j<m;j++)
     maxi=max(maxi,d[i][j]);
int flag=0;
for(int i=0;i<n;i++)
{
   for(int j=0;j<m;j++)
      {
        if(d[i][j]==maxi)
        {
          cout<<j+1<<" "<<i+1<<endl;
          flag=1;
          break;
        }
      }
   if(flag==1)
    break;
}
}
signed main(){
    ios_base::sync_with_stdio(false);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	ifstream fd;
	ofstream myfile;
	fd.open("input.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2004; ++i)
	{
		for (int j = 0; j < 2004; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		fd >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	myfile.open("output.txt");
	myfile << ans.first << " " << ans.second << endl;
	fd.close();
	myfile.close();
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	fstream fd;
	fd.open("input.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2005; ++i)
	{
		for (int j = 0; j < 2005; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		cin >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	fd << ans.first << " " << ans.second << endl;
	fd.close();
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	ifstream fd;
	ofstream myfile;
	fd.open("input.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2004; ++i)
	{
		for (int j = 0; j < 2004; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		cin >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	myfile.open("output.txt");
	myfile << ans.first << " " << ans.second << endl;
	fd.close();
	myfile.close();
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	ifstream fd;
	ofstream myfile;
	fd.open("input.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2004; ++i)
	{
		for (int j = 0; j < 2004; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		fd >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	ans.first = u;
	ans.second = v;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	myfile.open("output.txt");
	myfile << ans.first << " " << ans.second << endl;
	fd.close();
	myfile.close();
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	ifstream fd;
	ofstream myfile;
	fd.open("input.txt");
	myfile.open("output.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2004; ++i)
	{
		for (int j = 0; j < 2004; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		cin >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	myfile << ans.first << " " << ans.second << endl;
	fd.close();
	myfile.close();
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	cin >> n >> m;
	cin >> k;

	for (int i = 0; i < 2005; ++i)
	{
		for (int j = 0; j < 2005; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		cin >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	cout << ans.first << " " << ans.second << endl;
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
#define pii pair<int,int>

const int MOD = 1e7+7;

int dist[2005][2005];
std::vector<pii> st;

int isInBounds(int x, int y, int n, int m) {
	if(x > 0 && y > 0 && x <= n && y <= m) return 1;
	return 0;
}

int main(int argc, char const *argv[])
{
	int n,m,k,u,v;
	fstream fd;
	ofstream myfile;
	fd.open("input.txt");
	myfile.open("output.txt");
	fd >> n >> m;
	fd >> k;

	for (int i = 0; i < 2005; ++i)
	{
		for (int j = 0; j < 2005; ++j)
		{
			dist[i][j] = MOD;
		}
	}

	for (int i = 0; i < k; ++i)
	{
		cin >> u >> v;
		st.push_back(make_pair(u,v));
		dist[u][v] = 0;
	}

	for (int i = 0; i < st.size(); ++i)
	{
		pii loc = st[i];
		// cout << loc.first << " " << loc.second << endl;
		for (int k = -1; k < 2; ++k)
		{
			for(int l = -1; l < 2; ++l) {
				if(abs(l+k) == 1) {
					if(isInBounds(loc.first+k, loc.second+l, n, m)) {
						if(dist[loc.first+k][loc.second+l] > dist[loc.first][loc.second]+1) {
							dist[loc.first+k][loc.second+l] = dist[loc.first][loc.second]+1;
							st.push_back(make_pair(loc.first+k, loc.second+l));
						}
					}
				}
			}
		}
	}

	int _max = 0;
	pii ans;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (dist[i][j] > _max)
			{
				_max = dist[i][j];
				ans.first = i;
				ans.second = j;
				// cout << i << " " << j << endl;
			}
		}
	}

	myfile << ans.first << " " << ans.second << endl;
	fd.close();
	myfile.close();
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int C=2009,oo=0x3f3f3f3f;
queue<pair<int,int>>q;
int dis[C][C],n,m;
bool valid(int row,int col){
    return row>=0&&row<n&&col>=0&&col<m;
}
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
pair<int,int> BFS(){
    memset(dis,oo,sizeof dis);
    while(1){
        int ur=q.front().first,uc=q.front().second;
        q.pop();
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                q.push({vr,vc});
                dis[vr][vc]=dis[ur][uc]+1;
            }
        }
        if(q.empty())return{ur,uc};
    }

}
int x,y,t;
int main() {
    scanf("%d %d %d",&n,&m,&t);
    for(int i=0;i<t;i++){
        scanf("%d %d",&x,&y);
        q.push({--x,--y});
        dis[x][y]=0;
    }
    pair<int,int>ans=BFS();
    cout << (ans.first)+1 << " " << (ans.second)+1;
return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int C=2009,oo=0x3f3f3f3f;
queue<pair<int,int>>q;
int dis[C][C],n,m,ur,uc;
bool valid(int row,int col){
    return row>=0&&row<n&&col>=0&&col<m;
}
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
void BFS(){
    while(!q.empty()){
        ur=q.front().first,uc=q.front().second;
        q.pop();
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                q.push({vr,vc});
                dis[vr][vc]=dis[ur][uc]+1;
            }
        }
    }

}
int x,y,t;
int main() {
    scanf("%d %d %d",&n,&m,&t);
    memset(dis,oo,sizeof dis);
    for(int i=0;i<t;i++){
        scanf("%d %d",&x,&y);
        q.push({--x,--y});
        dis[x][y]=0;
    }
    BFS();
    printf("%d %d",ur+1,uc+1);
return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int C=2009,oo=0x3f3f3f3f;
queue<pair<int,int>>q;
int dis[C][C],n,m;
bool valid(int row,int col){
    return row>0&&row<=n&&col>0&&col<=m;
}
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
pair<int,int> BFS(){
    memset(dis,oo,sizeof dis);
    while(!q.empty()){
        int ur=q.front().first,uc=q.front().second;
        q.pop();
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                q.push({vr,vc});
                dis[vr][vc]=dis[ur][uc]+1;
            }
        }
        if(q.empty())return{ur,uc};
    }

}
int x,y,t;
int main() {
    scanf("%d %d %d",&n,&m,&t);
    for(int i=0;i<t;i++){
        scanf("%d %d",&x,&y);
        q.push({x,y});
        dis[x][y]=0;
    }
    pair<int,int>ans=BFS();
    printf("%d %d",ans.first,ans.second);
return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int o=2005,oo=0x3f3f3f3f;
int dis[o][o],n,m,t,x,y,ur,uc;
int dr[]={-1,1,0,0},dc[]={0,0,1,-1};
queue<pair<int,int>>q;
bool valid (int row,int col){
    return row>0&&row<=n&&col>0&&col<=m;
}
void BFS(){
    while(!q.empty()){
        ur=q.front().first;
        uc=q.front().second;
        q.pop();
        //printf("%d %d\n",ur,uc);
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                dis[vr][vc]=dis[ur][uc]+1;
                q.push({vr,vc});
            }
        }
    }
}
int main(){
        scanf("%d %d %d",&n,&m,&t);
        memset(dis,oo,sizeof dis);
        for(int i=0;i<t;i++){
            scanf("%d %d",&x,&y);
            q.push({x,y});
            dis[x][y]=0;
        }
        BFS();
        printf("%d %d",ur,uc);
        return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int C=2005,oo=0x3f3f3f3f;
queue<pair<int,int>>q;
int dis[C][C],n,m;
bool valid(int row,int col){
    return row>0&&row<n&&col>0&&col<m;
}
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
pair<int,int> BFS(){
    memset(dis,oo,sizeof dis);
    while(!q.empty()){
        int ur=q.front().first,uc=q.front().second;
        q.pop();
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                q.push({vr,vc});
                dis[vr][vc]=dis[ur][uc]+1;
            }
        }
        if(q.empty())return{ur,uc};
    }

}
int x,y,t;
int main() {
    scanf("%d %d %d",&n,&m,&t);
    for(int i=0;i<t;i++){
        scanf("%d %d",&x,&y);
        q.push({x,y});
        dis[x][y]=0;
    }
    pair<int,int>ans=BFS();
    printf("%d %d",ans.first,ans.second);
return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int o=2005,oo=0x3f3f3f3f;
int dis[o][o],n,m,t,x,y,ur,uc;
int dr[]={-1,1,0,0},dc[]={0,0,1,-1};
queue<pair<int,int>>q;
bool valid (int row,int col){
    return row>0&&row<=n&&col>0&&col<=m;
}
void BFS(){
    while(!q.empty()){
        ur=q.front().first;
        uc=q.front().second;
        q.pop();
        //printf("%d %d\n",ur,uc);
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                dis[vr][vc]=dis[ur][uc]+1;
                q.push({vr,vc});
            }
        }
    }
}
int main(){
    cin >> n >> m >> t;
        memset(dis,oo,sizeof dis);
        for(int i=0;i<t;i++){
            cin >> x >> y;
            q.push({x,y});
            dis[x][y]=0;
        }
        BFS();
        printf("%d %d",ur,uc);
        return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int o=2005,oo=0x3f3f3f3f;
int dis[o][o],n,m,t,x,y,ur,uc;
int dr[]={-1,1,0,0},dc[]={0,0,1,-1};
queue<pair<int,int>>q;
bool valid (int row,int col){
    return row>0&&row<=n&&col>0&&col<=m;
}
void BFS(){
    while(!q.empty()){
        ur=q.front().first;
        uc=q.front().second;
        q.pop();
        //printf("%d %d\n",ur,uc);
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                dis[vr][vc]=dis[ur][uc]+1;
                q.push({vr,vc});
            }
        }
    }
}
int main(){
    ifstream in("input.txt");
    in >> n >> m >> t;
        memset(dis,oo,sizeof dis);
        for(int i=0;i<t;i++){
            in >> x >> y;
            q.push({x,y});
            dis[x][y]=0;
        }
        BFS();
        ofstream out("output.txt");
        out << ur << " " << uc;
        return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int C=2009,oo=0x3f3f3f3f;
queue<pair<int,int>>q;
int dis[C][C],n,m;
bool valid(int row,int col){
    return row>=0&&row<n&&col>=0&&col<m;
}
int dr[]={-1,1,0,0};
int dc[]={0,0,-1,1};
pair<int,int> BFS(){
    while(1){
        int ur=q.front().first,uc=q.front().second;
        q.pop();
        for(int i=0;i<4;i++){
            int vr=ur+dr[i],vc=uc+dc[i];
            if(valid(vr,vc)&&dis[vr][vc]==oo){
                q.push({vr,vc});
                dis[vr][vc]=dis[ur][uc]+1;
            }
        }
        if(q.empty())return{ur,uc};
    }

}
int x,y,t;
int main() {
    scanf("%d %d %d",&n,&m,&t);
    memset(dis,oo,sizeof dis);
    for(int i=0;i<t;i++){
        scanf("%d %d",&x,&y);
        q.push({--x,--y});
        dis[x][y]=0;
    }
    pair<int,int>ans=BFS();
    cout << (ans.first)+1 << " " << (ans.second)+1;
return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof a) ;
#define vi vector<int>
#define vit vector<int> :: iterator
#define all(ans) ans.begin(),ans.end()
//#define sz(a) int(a.size())
#define ub upper_bound
#define lb lower_bound
#define create(Name,N,M,val) vector<vector<int> > Name(N,vector<int>(M,val))
#define ull unsigned long long
#define ll long long
#define db double
#define ldb long double
#define fl float
#define rep(i,a,b) for(int i=a;i<b;i++)
#define lrep(i,a,b) for(ll i=a;i<b;i++)
//#define all(c) c.begin(),c.end()
#define tr(c,it) for(typeof(c.begin()) it=c.begin();it!=c.end();it++)
#define mpr make_pair
#define pb push_back
#define fr first
#define sn second
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
bool vis[2001][2001];
void solve()
{
int n,m; cin>>n>>m;
rep(i,1,n+1)
rep(j,1,m+1)
{ vis[i][j]=0; }
int k,ax,ay; cin>>k;
queue< pair<int,int> >q;
rep(i,0,k)
{ cin>>ax>>ay;
q.push({ax,ay});
vis[ax][ay]=1; }
pair < int,int > ans;
while(!q.empty())
{
	pair < int,int > p;
	p=q.front();
	ans=p;
	q.pop();
	int xx=p.first;
	int yy=p.second;
	rep(j,0,4)
	{
	int nx=xx+dx[j];
	int ny=yy+dy[j];
	if(nx>0 && nx<=n && ny>0 && ny<=m && vis[nx][ny]==0)
	{
	vis[nx][ny]=1;
	q.push({nx,ny});
	}
	}
}
cout<<ans.fr<<' '<<ans.sn;
return;
}
int main()
{
ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t=1;
//	cin>>t;
while(t--)
{
solve();
}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof a) ;
#define vi vector<int>
#define vit vector<int> :: iterator
#define all(ans) ans.begin(),ans.end()
//#define sz(a) int(a.size())
#define ub upper_bound
#define lb lower_bound
#define create(Name,N,M,val) vector<vector<int> > Name(N,vector<int>(M,val))
#define ull unsigned long long
#define ll long long
#define db double
#define ldb long double
#define fl float
#define rep(i,a,b) for(int i=a;i<b;i++)
#define lrep(i,a,b) for(ll i=a;i<b;i++)
//#define all(c) c.begin(),c.end()
#define tr(c,it) for(typeof(c.begin()) it=c.begin();it!=c.end();it++)
#define mpr make_pair
#define pb push_back
#define fr first
#define sn second
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
void solve()
{
int n,m,k; cin>>n>>m>>k;
bool vis[n+1][m+1];
rep(i,1,n+1)
rep(j,1,m+1)
vis[i][j]=0;
int ax,ay;
queue< pair<int,int> >q;
rep(i,0,k)
{ cin>>ax>>ay;
q.push({ax,ay});
vis[ax][ay]=1; }
pair < int,int > ans;
while(!q.empty())
{
	ans=q.front();
	q.pop();
	int xx=ans.first;
	int yy=ans.second;
	rep(j,0,4)
	{
	int nx=xx+dx[j];
	int ny=yy+dy[j];
	if(nx>0 && nx<=n && ny>0 && ny<=m && vis[nx][ny]==0)
	{
	vis[nx][ny]=1;
	q.push({nx,ny});
	}
	}
}
cout<<ans.fr<<' '<<ans.sn;
return;
}
int main()
{
ifstream cin("input.txt");
    ofstream cout("output.txt");
ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t=1;
//	cin>>t;
while(t--)
{
solve();
}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define ll long long
#define rep(i,a,b) for(int i=a;i<b;i++)
#define pb push_back
#define fr first
#define sn second
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
bool vis[2002][2002];
void solve()
{
int n,m,k; cin>>n>>m>>k;
//bool vis[n+1][m+1];
rep(i,1,n+1)
rep(j,1,m+1)
vis[i][j]=0;
int ax,ay;
queue< pair<int,int> >q;
rep(i,0,k)
{ cin>>ax>>ay;
q.push({ax,ay});
vis[ax][ay]=1; }
pair < int,int > ans;
while(!q.empty())
{
	ans=q.front();
	q.pop();
	int xx=ans.first;
	int yy=ans.second;
	rep(j,0,4)
	{
	int nx=xx+dx[j];
	int ny=yy+dy[j];
	if(nx>0 && nx<=n && ny>0 && ny<=m && vis[nx][ny]==0)
	{
	vis[nx][ny]=1;
	q.push({nx,ny});
	}
	}
}
cout<<ans.fr<<' '<<ans.sn;
return;
}
int main()
{
ifstream cin("input.txt");
    ofstream cout("output.txt");
ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t=1;
//	cin>>t;
while(t--)
{
solve();
}
return 0;
}