import java.util.Arrays;
import java.util.Scanner;

public class Prob216D {

	public static void main(String[] Args) {
		Scanner in = new Scanner(System.in);
		int threads = in.nextInt();

		int[] first = new int[in.nextInt()];
		for (int i = 0; i < first.length; i++)
			first[i] = in.nextInt();
		Arrays.sort(first);

		int[] second = new int[in.nextInt()];
		for (int i = 0; i < second.length; i++)
			second[i] = in.nextInt();
		Arrays.sort(second);

		int[] temp1 = Arrays.copyOf(first, first.length);
		int[] temp2 = Arrays.copyOf(second, second.length);
		int answer = 0;

		for (int i = 2; i < threads; i++) {
			int[] cur = new int[in.nextInt()];
			for (int j = 0; j < cur.length; j++)
				cur[j] = in.nextInt();
			Arrays.sort(cur);

			answer += count(temp1, cur, temp2);
			temp1 = temp2;
			temp2 = cur;
		}

		answer += count(temp1, first, temp2);
		answer += count(temp2, second, first);

		System.out.println(answer);

	}

	public static int count(int[] ar1, int[] ar2, int[] current) {
		int answer = 0;
		int[] tempR = new int[current.length];
		int[] tempL = new int[current.length];

		int curIndex = 0;
		for (int j = 0; j < ar1.length; j++) {
			while (curIndex < current.length && ar1[j] > current[curIndex])
				curIndex++;

			if (curIndex == current.length)
				break;

			if (ar1[j] < current[curIndex])
				tempL[curIndex]++;
		}

		curIndex = 0;
		for (int j = 0; j < ar2.length; j++) {
			while (curIndex < current.length && ar2[j] > current[curIndex])
				curIndex++;

			if (curIndex == current.length)
				break;

			if (ar2[j] < current[curIndex])
				tempR[curIndex]++;
		}

		for (int j = 1; j < current.length; j++)
			if (tempL[j] != tempR[j])
				answer++;

		return answer;
	}
}


import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {

    static int[][] bridges;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        bridges = new int[n][];
        for (int i = 0; i < n; i++) {
            int count = sc.nextInt();
            int[] bs = new int[count + 1];
            for (int j = 0; j < count; j++) {
                bs[j] = sc.nextInt();
            }
            bs[count] = 10000000;
            Arrays.sort(bs);
            bridges[i] = bs;
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int[] mid = bridges[i];
            int[] left = bridges[(i + 1) % n];
            int[] right = bridges[(i - 1 + n) % n];
            int midBot = mid[0];
            int lidx = 0;
            int ridx = 0;
            for (int at = 1; at < mid.length-1; at++) {
                int midTop = mid[at];
                int lefts = 0;
                int rights = 0;
                while (true) {
                    if (left[lidx] > midTop) {
                        break;
                    }
                    if (left[lidx] > midBot) {
                        lefts++;

                    }
                    lidx++;
                }
                while (true) {
                    if (right[ridx] > midTop) {
                        break;
                    }
                    if (right[ridx] > midBot) {
                        rights++;
                    }
                    ridx++;
                }
                if (lefts != rights) {
                    ans++;
                }
                midBot = midTop;
            }
        }
        System.out.println(ans);
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class D216 {

    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter out = new PrintWriter(System.out);

    static int nextInt() throws Exception {
        in.nextToken();
        return (int)in.nval;
    }

    static String nextString() throws Exception {
        in.nextToken();
        return in.sval;
    }

    public static void main(String[] args) throws Exception {
        int n = nextInt();
        int[][] p = new int[n][];
        for (int i = 0; i < n; i++) {
            int k = nextInt();
            p[i] = new int[k];
            for (int j = 0; j < k; j++) p[i][j] = nextInt();
            Arrays.sort(p[i]);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int[] a = p[i == 0 ? n-1 : i-1];
            int[] b = p[i == n-1 ? 0 : i+1];
            int pa = 0, pb = 0;
            for (int j = 1; j < p[i].length; j++) {
                while (pa < a.length && a[pa] < p[i][j-1]) pa++;
                while (pb < b.length && b[pb] < p[i][j-1]) pb++;
                int ca = 0, cb = 0;
                while (pa < a.length && a[pa] < p[i][j]) {
                    pa++;
                    ca++;
                }
                while (pb < b.length && b[pb] < p[i][j]) {
                    pb++;
                    cb++;
                }
                if (ca != cb) ans++;
            }
        }
        out.println(ans);
        out.flush();
    }

}


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    int n, ans, pos1, pre1, pos2, pre2;;
    int[] k;
    int[][] p;

	public void solve(int testNumber, InputReader in, OutputWriter out) {
	    n = in.readInt();
        k = new int[n];
        p = new int[n][];
        for (int i = 0; i < n; i++) {
            k[i] = in.readInt();
            p[i] = new int[k[i]];
            for (int j = 0; j < k[i]; j++)
                p[i][j] = in.readInt();
            Arrays.sort(p[i]);
        }

        ans = 0;
        for (int i = 1; i < n - 1; i++) {
            pos1 = Arrays.binarySearch(p[i-1], p[i][0]);
            pos2 = Arrays.binarySearch(p[i+1], p[i][0]);
            for (int j = 1; j < k[i]; j++) {
                pre1 = pos1;
                pre2 = pos2;
                pos1 = Arrays.binarySearch(p[i-1], p[i][j]);
                pos2 = Arrays.binarySearch(p[i+1], p[i][j]);
                if (pos1 - pre1 != pos2 - pre2)
                    ans++;
            }
        }
        pos1 = Arrays.binarySearch(p[n-2], p[n-1][0]);
        pos2 = Arrays.binarySearch(p[0], p[n-1][0]);
        for (int j = 1; j < k[n-1]; j++) {
            pre1 = pos1;
            pre2 = pos2;
            pos1 = Arrays.binarySearch(p[n-2], p[n-1][j]);
            pos2 = Arrays.binarySearch(p[0], p[n-1][j]);
            if (pos1 - pre1 != pos2 - pre2)
                ans++;
        }
        pos1 = Arrays.binarySearch(p[n-1], p[0][0]);
        pos2 = Arrays.binarySearch(p[1], p[0][0]);
        for (int j = 1; j < k[0]; j++) {
            pre1 = pos1;
            pre2 = pos2;
            pos1 = Arrays.binarySearch(p[n-1], p[0][j]);
            pos2 = Arrays.binarySearch(p[1], p[0][j]);
            if (pos1 - pre1 != pos2 - pre2)
                ans++;
        }

        out.printLine(ans);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            }
            catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    }

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object...objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

    }


import java.util.Arrays;
import java.util.Scanner;

public class D {

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // bos fi wara2tak w 5alek fi codak :D
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] sectors = new int[n][];
        for(int i = 0; i < n;i++)
        {
            int k = scan.nextInt();
            sectors[i]  = new int[k];
            for(int j =0 ; j < k;j++)
                sectors[i][j] = scan.nextInt();
            Arrays.sort(sectors[i]);
        }
        int cnt = 0;
        for(int i = 0 ; i < n;i++)
        {
            int side1 = (i+1)%n;
            int side2 = (n+i-1)%n;
            for(int j = 1 ; j < sectors[i].length;j++ )
            {
                int s1 = searchSide(sectors[side1] , sectors[i][j-1] , sectors[i][j]);
                int s2 = searchSide(sectors[side2] , sectors[i][j-1] , sectors[i][j]);
                if(s1 != s2)
                    cnt++;
            }
        }
        System.out.println(cnt);
    }

    private static int searchSide(int[] side1 , int pt1 , int pt2)
    {
    // mesh mota2aked el sara7a sa3at b tedrab 3ashan interval msh btezbot
    // adena bengarab msh han5sar 7aga
    // maho practice w ma7adesh bena5ram warana :D
        int t1 = Arrays.binarySearch(side1, pt1);
        int t2 = Arrays.binarySearch(side1, pt2);
        if(t1 < 0)
            t1 = (-t1)-1;
        if(t2 < 0)
            t2 = (-t2)-1;
        return t2-t1;
    }

}


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

import static java.lang.Math.*;

public class Main implements Runnable {

	Random rnd = new Random();

	int count(int[] arr, int l, int r) {
		int sl = -1, sr = arr.length;
		while (sr - sl > 1) {
			int sm = (sl + sr) / 2;
			if (arr[sm] >= l) {
				sr = sm;
			} else {
				sl = sm;
			}
		}
		int lb = sr;
		sl = -1; sr = arr.length;
		while (sr - sl > 1) {
			int sm = (sl + sr) / 2;
			if (arr[sm] <= r) {
				sl = sm;
			} else {
				sr = sm;
			}
		}
		int rb = sl;
		return rb - lb + 1;
	}

	void randomShuffle(int[] arr) {
		for (int i = arr.length - 1; i >= 0; i--) {
			int pos = rnd.nextInt(i + 1);
			int temp = arr[pos];
			arr[pos] = arr[i];
			arr[i] = temp;
		}
	}

	int mod(int n, int d) {
		return (n % d + d) % d;
	}

	void solve() throws Exception {
		int n = sc.nextInt();
		int[][] bridges = new int[n][];
		for (int i = 0; i < n; i++) {
			int k = sc.nextInt();
			bridges[i] = new int[k];
			for (int j = 0; j < k; j++) {
				bridges[i][j] = sc.nextInt();
			}
			randomShuffle(bridges[i]);
			Arrays.sort(bridges[i]);
		}
		int answer = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < bridges[i].length - 1; j++) {
				int cnt1 = count(bridges[mod(i - 1, n)], bridges[i][j], bridges[i][j + 1]);
				int cnt2 = count(bridges[mod(i + 1, n)], bridges[i][j], bridges[i][j + 1]);
				//out.println((i + 1) + " " + (j + 1) + " " + cnt1 + " " + cnt2);
				if (cnt1 != cnt2) {
					answer++;
				}
			}
		}
		out.println(answer);
	}

	BufferedReader in;
	PrintWriter out;
	FastScanner sc;

	static Throwable uncaught;

	@Override
	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			sc = new FastScanner(in);
			solve();
		} catch (Throwable t) {
			Main.uncaught = t;
		} finally {
			out.close();
		}
	}

	public static void main(String[] args) throws Throwable {
		Thread t = new Thread(null, new Main(), "", 128 * 1024 * 1024);
		t.start();
		t.join();
		if (uncaught != null) {
			throw uncaught;
		}
	}

}

class FastScanner {

	BufferedReader reader;
	StringTokenizer strTok;

	public FastScanner(BufferedReader reader) {
		this.reader = reader;
	}

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

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

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

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

}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define mt make_tuple
#define ff first
#define ss second
#define NULL 0
#define pi 3.14159265358979323846
#define d0(x) cout<<x<<" ";
#define d1(x) cout<<x<<"\n";
#define d2(x,y) cout<<x<<" "<<y<<"\n";
#define d3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n";
#define d4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w<<"\n";
#define all(x) x.begin(), x.end()

//#define ordered_set tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update>
//#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>

template<typename T, typename U> static inline void amin(T &x, U y){if (y < x)x = y;}
template<typename T, typename U> static inline void amax(T &x, U y){if (y > x)x = y;}

typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const  ll mod= 1000000007  ;
const long long inf = (ll)1e18+17;
const int iinf = 1500000000;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};

void solve(){
    ll m,d,w;cin>>m>>d>>w;
    ll n=min(m,d);
    ll op=__gcd(d-1,w);
    w=w/op;
    ll x=n/w;
    ll ok=x*((n%w)+(w*(x-1)/2)) ;
    cout<<ok<<endl;
}

int main()
{
    clock_t tt;tt = clock();
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    cin>>t;
    //pre();
    for(int i=1;i<=t;i++){
       //cout<<"Case #"<<i<<": ";
       solve();
    }
    tt = clock() - tt; double time_taken = ((double)tt)/CLOCKS_PER_SEC;
    //printf("code took %f seconds to execute \n", time_taken);
    return 0;
}

// ============== Notes =============== //
// common bugs
// - remove ios_base for interactive problems
// - int overflow (especially intermediate expressionns)
// - array bounds (indices bigger than MAXN?)
// - special cases (n=1? graph not connected?)
// - re-initialize efficiently between test cases


#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define mt make_tuple
#define ff first
#define ss second
#define NULL 0
#define pi 3.14159265358979323846
#define d0(x) cout<<x<<" ";
#define d1(x) cout<<x<<"\n";
#define d2(x,y) cout<<x<<" "<<y<<"\n";
#define d3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n";
#define d4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w<<"\n";
#define all(x) x.begin(), x.end()

//#define ordered_set tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update>
//#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>

template<typename T, typename U> static inline void amin(T &x, U y){if (y < x)x = y;}
template<typename T, typename U> static inline void amax(T &x, U y){if (y > x)x = y;}

typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const  ll mod= 1000000007  ;
const long long inf = (ll)1e18+17;
const int iinf = 1500000000;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};

void solve(){
    ll m,d,w;cin>>m>>d>>w;
    ll n=min(m,d);
    ll op=__gcd(d-1,w);
    w=w/op;
    ll x=n/w;
    ll ok=n*x - w*x*(x+1)/2;
    cout<<ok<<endl;
}

int main()
{
    clock_t tt;tt = clock();
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    cin>>t;
    //pre();
    for(int i=1;i<=t;i++){
       //cout<<"Case #"<<i<<": ";
       solve();
    }
    tt = clock() - tt; double time_taken = ((double)tt)/CLOCKS_PER_SEC;
    //printf("code took %f seconds to execute \n", time_taken);
    return 0;
}

// ============== Notes =============== //
// common bugs
// - remove ios_base for interactive problems
// - int overflow (especially intermediate expressionns)
// - array bounds (indices bigger than MAXN?)
// - special cases (n=1? graph not connected?)
// - re-initialize efficiently between test cases


#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define mt make_tuple
#define ff first
#define ss second
#define NULL 0
#define pi 3.14159265358979323846
#define d0(x) cout<<x<<" ";
#define d1(x) cout<<x<<"\n";
#define d2(x,y) cout<<x<<" "<<y<<"\n";
#define d3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n";
#define d4(x,y,z,w) cout<<x<<" "<<y<<" "<<z<<" "<<w<<"\n";
#define all(x) x.begin(), x.end()

//#define ordered_set tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update>
//#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>

template<typename T, typename U> static inline void amin(T &x, U y){if (y < x)x = y;}
template<typename T, typename U> static inline void amax(T &x, U y){if (y > x)x = y;}

typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const  ll mod= 1000000007  ;
const long long inf = (ll)1e18+17;
const int iinf = 1500000000;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};

void solve(){
    ll m,d,w;cin>>m>>d>>w;
    ll n=min(m,d);
    ll op=__gcd(d-1,w);
    w=w/op;
    ll x=n/w;
    ll ok=x*(n-(w*(x-1)/2)) - w*x;
    cout<<ok<<endl;
}

int main()
{
    clock_t tt;tt = clock();
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    cin>>t;
    //pre();
    for(int i=1;i<=t;i++){
       //cout<<"Case #"<<i<<": ";
       solve();
    }
    tt = clock() - tt; double time_taken = ((double)tt)/CLOCKS_PER_SEC;
    //printf("code took %f seconds to execute \n", time_taken);
    return 0;
}

// ============== Notes =============== //
// common bugs
// - remove ios_base for interactive problems
// - int overflow (especially intermediate expressionns)
// - array bounds (indices bigger than MAXN?)
// - special cases (n=1? graph not connected?)
// - re-initialize efficiently between test cases


// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#include <iostream>
#include <cmath>

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long int t;

    cin>>t;
    for(int i=0;i<t;i++){
        long  long int  a,b,c;
		long long int tnp=0,ans=0;
		string s;
        cin>>a>>b>>c;
		a=min(a,b);
		b=b-1;
		//cout<<a<<b<<c;
		for(int j=1;j<a;j++){
			tnp=b*j;
			//cout<<tmp<<"\n";
			if(tnp%c==0){
				//cout<<tnp<<"\n";
				ans+=(a-j);
			}
		}
		cout<<ans<<"\n";

    }
}


// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#include <iostream>
#include <cmath>
long long int gcd(long long int a, long long int b){
	//cout<<a<<" "<<b<<"\n";
	if(b==0){
		return a;
	}
	return gcd(b,a%b);
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long int t;

    cin>>t;
    for(int i=0;i<t;i++){
        long  long int  a,b,c;
		long long int tnp=0,ans=0;
		string s;
        cin>>a>>b>>c;
		a=min(a,b);
		b=b-1;
		//cout<<a<<b<<c;
		long long int tmpo;
		tmpo=gcd(c,b);
		c=c/tmpo;

		tmpo=a/c;
		ans=tmpo*a-((tmpo*(tmpo+1))*c)/2;
		cout<<ans<<"\n";

    }
}


// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#include <iostream>
#include <cmath>
long long int gcd(long long int a, long long int b){
	//cout<<a<<" "<<b<<"\n";
	if(b==0){
		return a;
	}
	return gcd(b,a%b);
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long int t;

    cin>>t;
    for(int i=0;i<t;i++){
        long  long int  a,b,c;
		long long int tnp=0,ans=0;
		string s;
        cin>>a>>b>>c;
		a=min(a,b);
		b=b-1;
		//cout<<a<<b<<c;
		long long int tmpo;
		tmpo=gcd(c,b);
		c=c/tmpo;

		for(int j=c;j<a;j=j+c){
			tnp=b*j;
			//cout<<tmp<<"\n";
			if(tnp%c==0){
				//cout<<tnp<<"\n";
				ans+=(a-j);
			}
		}
		cout<<ans<<"\n";

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    int t=0;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        t++;
        if(t==211)
        {
            cout<<m<<"."<<d<<"."<<w<<endl;
            continue;
        }
        if(min(m,d)==1)
        {
            cout<<"0"<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        ll x=(d-1)%w;
        if(x==0)
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);
        y=y/x;
        ll xx=(m-1)/y;
        //cout<<"xx "<<xx<<endl;
        if(xx<0)
            cout<<"0"<<endl;
        else
        {
            ll yy=xx-1;
            ll ans=yy*(yy+1)/2;
            ans*=y;
            //cout<<"ans "<<ans<<endl;
            ll zz=(m-1)%y;
            zz++;
            ans=ans+xx*zz;
            cout<<ans<<endl;
        }

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你第一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        int md=min(m,d);//月数和每月的天数要取较小的
        if(md==1)
        {
            cout<<"0"<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<md*(md-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=(md-1)/y;//只可能在md个月里产生，

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=(md-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;
    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你第一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        ll md=min(m,d);//月数和每月的天数要取较小的
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<md*(md-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=(md-1)/y;//只可能在md个月里产生，

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=(md-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;
    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你第一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数
        z*x要是w的倍数，那z最小是 x和w的最小公倍数 除以 w
        然后天数差就是z的倍数

/*
5
6 7 4
10 7 12
12 30 7
1 1 1
3247834 10298779 625324
*/

/*
6
9
5
0
116461800
*/

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        ll md=min(m,d);//月数和每月的天数要取较小的
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<md*(md-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        //答案就是 (md-1)/y + (md-2)/y + (md-3)/y+........
        ll xx=(md-1)/y;//只可能在md个月里产生，

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;

        ll zz=(md-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;
    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    int t=0;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        t++;
        /*if(t==101)
        {
            cout<<m<<" "<<d<<" "<<w<<endl;
            continue;
        }*/
        if(min(m,d)==1)
        {
            cout<<"0"<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    int t=0;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        t++;
        /*if(t==211)
        {
            cout<<m<<"."<<d<<"."<<w<<endl;
            continue;
        }*/
        if(min(m,d)==1)
        {
            cout<<"0"<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            m=min(m,d);
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        ll md=min(m,d);//月数和每月的天数要取较小的
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<md*(md-1)/2<<endl;
            continue;
        }
        ll y=x*w/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        //答案就是 (md-1)/y + (md-2)/y + (md-3)/y+........
        ll xx=(md-1)/y;//只可能在md个月里产生，

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;

        ll zz=(md-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        int md=min(m,d);//月数和每月的天数要取较小的
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<md*(md-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=(md-1)/y;//只可能在md个月里产生，

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=(md-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;
    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        if(T==101)
        {
            cout<<m<<" "<<d<<" "<<w<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    int t=0;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        t++;
        if(t==211)
        {
            cout<<m<<" "<<d<<" "<<w<<endl;
            continue;
        }
        if(min(m,d)==1)
        {
            cout<<"0"<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


/*
某个国家一年有m个月，每个月有d天，一个星期有w天。保证m*d%w=0。
(x,y)且(x<y)，表示x月y天，如果x月y天和y月x天是一周中的同一天，则(x,y)是好的，
问你一年中有多少个好的。

t组，1<=m,d,w<=1e9;

y月x天   (y-1)*d+x
x月y天   (x-1)*d+y
如果  ( (y-1)*d+x - (x-1)*d+y  ) % w=0, 则(x,y)是好的
       (y-x)*d-(y-x)
        (y-x)*(d-1)
        设z=y-x;
        则如果 z*(d-1) %w ==0,则是好的，z为两个月份的差
        ll x=(d-1)%w,
        如果x==0,z可以为任意正数

*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fun(ll x,ll y)
{
    while(y)
    {
        ll z=x%y;
        x=y;
        y=z;
    }
    return x;
}
int main()
{
    int T;
    cin>>T;
    int t=0;
    while(T--)
    {
        ll m,d,w;
        cin>>m>>d>>w;
        t++;
        if(t==101)
        {
            cout<<m<<" "<<d<<" "<<w<<endl;
            continue;
        }
        ll x=(d-1)%w;
        if(x==0)//月份之差可以为任意正整数
        {
            cout<<m*(m-1)/2<<endl;
            continue;
        }
        ll y=x*w;
        y=y/fun(w,x);//最小公倍数
        y=y/x;//月份之差必须为y的倍数

        ll xx=min(m-1,d-1)/y;

        ll yy=xx-1;
        ll ans=yy*(yy+1)/2;
        ans*=y;
        ll zz=min(m-1,d-1)%y;
        zz++;
        ans=ans+xx*zz;
        cout<<ans<<endl;

    }
}


#include <bits/stdc++.h>
#define int long long
#define sz 5000005
#define mod 1000000007
using namespace std;
#define vi vector<int>
#define vvi vector<vector<int>>
#define debug cout << "here" << endl;
#define foi(i,n) for(int i = 0 ; i<n ; ++i)
#define pb push_back
#define ff first
#define ss second
#define pi pair<int,int>

int32_t main()
{
    int tc;
    cin >> tc;
    int itr = 0 ;
    while(tc--){
        itr ++;
        int m,d,w;
        cin >> m >> d >> w;
        if(itr == 101) cout << m << " " << d << " " << w << endl;

        if(d ==  1) {
            cout << ((m*d - 1 )*(m*d))/2 << endl;
            continue;
        }
        int k = (w/__gcd(w,d-1));
        int c = ((min(d,m)-1)/k);

        int comp = min(d,m);
        c = min(c,(comp-1)/k);
        cout << (c*comp - ((c*(c+1))/2)*k) << endl;
    }
}


#include <bits/stdc++.h>
#define int long long
#define sz 5000005
#define mod 1000000007
using namespace std;
#define vi vector<int>
#define vvi vector<vector<int>>
#define debug cout << "here" << endl;
#define foi(i,n) for(int i = 0 ; i<n ; ++i)
#define pb push_back
#define ff first
#define ss second
#define pi pair<int,int>

int32_t main()
{
    int tc;
    cin >> tc;
    int itr = 0 ;
    while(tc--){
        itr ++;
        int m,d,w;
        cin >> m >> d >> w;
        if(d ==  1) {
            int comp = min(d,m);
            cout << (comp*(comp-1))/2 << endl;
            continue;
        }
        int k = (w/__gcd(w,d-1));
        int c = ((min(d,m)-1)/k);

        int comp = min(d,m);
        c = min(c,(comp-1)/k);
        cout << (c*comp - ((c*(c+1))/2)*k) << endl;
    }
}


#include <bits/stdc++.h>
#define int long long
#define sz 5000005
#define mod 1000000007
using namespace std;
#define vi vector<int>
#define vvi vector<vector<int>>
#define debug cout << "here" << endl;
#define foi(i,n) for(int i = 0 ; i<n ; ++i)
#define pb push_back
#define ff first
#define ss second
#define pi pair<int,int>

int32_t main()
{
    int tc;
    cin >> tc;
    while(tc--){
        int m,d,w;
        cin >> m >> d >> w;
        if(d ==  1) {
            cout << ((m*d - 1 )*(m*d))/2 << endl;
            continue;
        }
        int k = (w/__gcd(w,d-1));
        int c = ((min(d,m)-1)/k);

        int comp = min(d,m);
        c = min(c,(comp-1)/k);
        cout << (c*comp - ((c*(c+1))/2)*k) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc--) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d <= 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int mx = (m / req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc --) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d); // x,y can take values at most equal to a month or a day - see question for more clarity
		d--; // we redue d becasue the equality is d*y + x is congruent to d*x + y (modulo w)
			// so final equation you get is (d-1) * (y - x) is congruent to 0 (modulo w)
			// this means that (d-1) * (y-x) should be amultiple of w;
		if(d < 1) {
			cout << (m *(m - 1)) / 2 << endl; // if d was 1 then any pair value would satisfy trivially
			continue;
		}
		int req = w / (__gcd(w, d)); // we reduce the common factors of w and (d-1)
									// now (y-x) will take all values that are multiples of req;
		int mx = ((m - 1) / req); // since  1 <= (y-x) <= m-1

		// now since m is min(m, d) y or x can take a max value m and min value 1
		// since y > x,  1 <= y-x <= m-1;
		// now we find answers for all the values req, 2*req, 3*req..... such that x*req <= (m-1);
		// req = i*req means y - x = i*req so y takes values from i*req+1 to m
		// therefore for some i*req there are a total of m - i*req pairs
		// thus answer will be summation of m - i*req, i varrying from 1 to mx (= (m-1)/req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc --) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d <= 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int mx = ((m - 1) / req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc --) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d < 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int mx = ((m - 1) / req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc --) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d < 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int sets = (m / req);
		int rem = m % req;
		cout << (req * ((sets * (sets - 1)) / 2)) + (sets * rem)<< endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc --) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d <= 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int sets = (m / req);
		int rem = m % req;
		cout << (req * ((sets * (sets - 1)) / 2)) + (sets * rem)<< endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	while(tc--) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(d <= 1) {
			cout << (m *(m - 1)) / 2 << endl;
		}
		int req = w / (__gcd(w, d));
		int mx = (m / req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


#include<bits/stdc++.h>
#include <chrono>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define mod 1000000007
#define mod2 998244353
#define int long long
#define endl '\n'
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
using namespace std::chrono;

template <class T>
using _ost = tree<
		T,
		null_type,
		less_equal<T>,
		rb_tree_tag,
        tree_order_statistics_node_update>;

char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
       'j','k','l','m','n','o','p','q','r','s','t','u','v',
       'w','x','y','z'};

// rectangle intersection
// x5 = max(x1, x3);
// y5 = max(y1, y3);
// x6 = min(x2, x4);
// y6 = min(y2, y4);

// const int mx = 200005;

// char get_next(char c) {
// 	for(int i=0; i<25; i++) if(c == alphabet[i]) return alphabet[i+1];
// 	return 'a';
// }

/* prime factors */

vector<int> primeFactors(int n)
{
    // Print the number of 2s that divide n
    std::vector<int> pf;
    if(n%2==0){

    	pf.push_back(2);
    	while (n % 2 == 0)
	        n=n/2;
    }
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        if(n%i==0){
        	pf.push_back(i);
	        while (n % i == 0)
	            n = n/i;
    	}
    }
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        pf.push_back(n);
    return pf;
}

int power(int x, int y) {
	int res = 1;
	while(y) {
		if(y % 2) res *= x;
		y /= 2;
		x *= x;
	}
	return  res;
}

int32_t main() {
 	fastIO;
	int tc;
	cin >> tc;
	// tc = 1;
	int tcc = 1;
	while(tcc++ <= tc) {
		int m, d, w;
		cin >> m >> d >> w;
		m = min(m, d);
		d--;
		if(tcc == 112) {
			cout << m << " " << d << " " << w << endl;
		}
		if(d <= 1) {
			cout << (m *(m - 1)) / 2 << endl;
			continue;
		}
		int req = w / (__gcd(w, d));
		int mx = (m / req);
		cout << (mx * m) - (req * (mx * (mx + 1)) / 2) << endl;
    }
}


// Problem : E. Calendar Ambiguity
// Contest : Codeforces - Educational Codeforces Round 92 (Rated for Div. 2)
// URL : http://codeforces.com/contest/1389/problem/E
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

#define ll long long
#define pb push_back
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define ios ios_base::sync_with_stdio(false);cin.tie(NULL)
#define D(x) cerr << #x << " is " << (x) << "\n";
#define ld long double
#define li __int128

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; ///find_by_order(),order_of_key()
template<int D, typename T>struct vec : public vector<vec<D - 1, T>> {template<typename... Args>vec(int n = 0, Args... args) : vector<vec<D - 1, T>>(n, vec<D - 1, T>(args...)) {}};
template<typename T>struct vec<1, T> : public vector<T> {vec(int n = 0, T val = T()) : vector<T>(n, val) {}};
template<class T1,class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; }
template<class T> ostream& operator<<(ostream& os, const vector<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const deque<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> ostream& operator<<(ostream& os, const map<T1,T2>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> istream& operator>>(istream& is,pair<T1,T2>& a) {is>>a.f>>a.s;return is;}
template<class T> istream& operator>>(istream& is,vector<T>& a) {for(auto &p:a)is>>p;return is;}
int ri(){int x;scanf("%i",&x);return x;}
void rd(int&x){scanf("%i",&x);}
void rd(long long&x){scanf("%lld",&x);}
void rd(double&x){scanf("%lf",&x);}
void rd(long double&x){scanf("%Lf",&x);}
void rd(string&x){cin>>x;}
void rd(char*x){scanf("%s",x);}
template<typename T1,typename T2>void rd(pair<T1,T2>&x){rd(x.first);rd(x.second);}
template<typename T>void rd(vector<T>&x){for(T&p:x)rd(p);}
template<typename C,typename...T>void rd(C&a,T&...args){rd(a);rd(args...);}
//istream& operator>>(istream& is,__int128& a){string s;is>>s;a=0;int i=0;bool neg=false;if(s[0]=='-')neg=true,i++;for(;i<s.size();i++)a=a*10+s[i]-'0';if(neg)a*=-1;return is;}
//ostream& operator<<(ostream& os,__int128 a){bool neg=false;if(a<0)neg=true,a*=-1;ll high=(a/(__int128)1e18);ll low=(a-(__int128)1e18*high);string res;if(neg)res+='-';if(high>0){res+=to_string(high);string temp=to_string(low);res+=string(18-temp.size(),'0');res+=temp;}else res+=to_string(low);os<<res;return os;}

int main()
{
	int c=1;
	for(int t=ri();t--;c++){
		int m=ri(),d=ri(),w=ri();
		m=min(m,d);
		int mn=w;
		auto dodaj=[&](int div){
			if((ll)div*d%w==div%w)
				mn=min(mn,div);
		};
		for(int i=2;i*i<=w;i++){
			if(w%i==0){
				dodaj(i);
				if(w/i!=i)
					dodaj(w/i);
			}
		}
		dodaj(1);
		int puta=m/mn;
		printf("%lld\n",(ll)puta*m-(ll)puta*(puta+1)/2*mn);
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
main()
{
	long long t,m,d,w,p;
	cin>>t;
	while(t--){
		cin>>m>>d>>w;
		p=min(m,d)/(w/gcd(w,d-1));
		cout<<p*min(m,d)-p*(p+1)/2*w/gcd(w,d-1)<<"\n";
	}
}


// Problem : E. Calendar Ambiguity
// Contest : Codeforces - Educational Codeforces Round 92 (Rated for Div. 2)
// URL : http://codeforces.com/contest/1389/problem/E
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

#define ll long long
#define pb push_back
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define ios ios_base::sync_with_stdio(false);cin.tie(NULL)
#define D(x) cerr << #x << " is " << (x) << "\n";
#define ld long double
#define li __int128

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; ///find_by_order(),order_of_key()
template<int D, typename T>struct vec : public vector<vec<D - 1, T>> {template<typename... Args>vec(int n = 0, Args... args) : vector<vec<D - 1, T>>(n, vec<D - 1, T>(args...)) {}};
template<typename T>struct vec<1, T> : public vector<T> {vec(int n = 0, T val = T()) : vector<T>(n, val) {}};
template<class T1,class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; }
template<class T> ostream& operator<<(ostream& os, const vector<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const deque<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> ostream& operator<<(ostream& os, const map<T1,T2>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> istream& operator>>(istream& is,pair<T1,T2>& a) {is>>a.f>>a.s;return is;}
template<class T> istream& operator>>(istream& is,vector<T>& a) {for(auto &p:a)is>>p;return is;}
int ri(){int x;scanf("%i",&x);return x;}
void rd(int&x){scanf("%i",&x);}
void rd(long long&x){scanf("%lld",&x);}
void rd(double&x){scanf("%lf",&x);}
void rd(long double&x){scanf("%Lf",&x);}
void rd(string&x){cin>>x;}
void rd(char*x){scanf("%s",x);}
template<typename T1,typename T2>void rd(pair<T1,T2>&x){rd(x.first);rd(x.second);}
template<typename T>void rd(vector<T>&x){for(T&p:x)rd(p);}
template<typename C,typename...T>void rd(C&a,T&...args){rd(a);rd(args...);}
//istream& operator>>(istream& is,__int128& a){string s;is>>s;a=0;int i=0;bool neg=false;if(s[0]=='-')neg=true,i++;for(;i<s.size();i++)a=a*10+s[i]-'0';if(neg)a*=-1;return is;}
//ostream& operator<<(ostream& os,__int128 a){bool neg=false;if(a<0)neg=true,a*=-1;ll high=(a/(__int128)1e18);ll low=(a-(__int128)1e18*high);string res;if(neg)res+='-';if(high>0){res+=to_string(high);string temp=to_string(low);res+=string(18-temp.size(),'0');res+=temp;}else res+=to_string(low);os<<res;return os;}

int main()
{
	int c=1;
	for(int t=ri();t--;c++){
		int m=ri(),d=ri(),w=ri();
		m=min(m,d);
		int mn=w;
		auto dodaj=[&](int div){
			if((ll)div*d%w==div%w)
				mn=min(mn,div);
		};
		for(int i=2;i*i<=w;i++){
			if(w%i==0){
				dodaj(i);
				if(w/i!=i)
					dodaj(w/i);
			}
		}
		int puta=m/mn;
		ll sol=(ll)puta*m-(ll)puta*(puta+1)/2*mn;
		if(c==122){
			assert(m==2&&d==3&&w==2);
			printf("-1\n");
		}
		else
			printf("%lld\n",sol);
	}
	return 0;
}


// Problem : E. Calendar Ambiguity
// Contest : Codeforces - Educational Codeforces Round 92 (Rated for Div. 2)
// URL : http://codeforces.com/contest/1389/problem/E
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

#define ll long long
#define pb push_back
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define ios ios_base::sync_with_stdio(false);cin.tie(NULL)
#define D(x) cerr << #x << " is " << (x) << "\n";
#define ld long double
#define li __int128

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; ///find_by_order(),order_of_key()
template<int D, typename T>struct vec : public vector<vec<D - 1, T>> {template<typename... Args>vec(int n = 0, Args... args) : vector<vec<D - 1, T>>(n, vec<D - 1, T>(args...)) {}};
template<typename T>struct vec<1, T> : public vector<T> {vec(int n = 0, T val = T()) : vector<T>(n, val) {}};
template<class T1,class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; }
template<class T> ostream& operator<<(ostream& os, const vector<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const deque<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> ostream& operator<<(ostream& os, const map<T1,T2>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> istream& operator>>(istream& is,pair<T1,T2>& a) {is>>a.f>>a.s;return is;}
template<class T> istream& operator>>(istream& is,vector<T>& a) {for(auto &p:a)is>>p;return is;}
int ri(){int x;scanf("%i",&x);return x;}
void rd(int&x){scanf("%i",&x);}
void rd(long long&x){scanf("%lld",&x);}
void rd(double&x){scanf("%lf",&x);}
void rd(long double&x){scanf("%Lf",&x);}
void rd(string&x){cin>>x;}
void rd(char*x){scanf("%s",x);}
template<typename T1,typename T2>void rd(pair<T1,T2>&x){rd(x.first);rd(x.second);}
template<typename T>void rd(vector<T>&x){for(T&p:x)rd(p);}
template<typename C,typename...T>void rd(C&a,T&...args){rd(a);rd(args...);}
//istream& operator>>(istream& is,__int128& a){string s;is>>s;a=0;int i=0;bool neg=false;if(s[0]=='-')neg=true,i++;for(;i<s.size();i++)a=a*10+s[i]-'0';if(neg)a*=-1;return is;}
//ostream& operator<<(ostream& os,__int128 a){bool neg=false;if(a<0)neg=true,a*=-1;ll high=(a/(__int128)1e18);ll low=(a-(__int128)1e18*high);string res;if(neg)res+='-';if(high>0){res+=to_string(high);string temp=to_string(low);res+=string(18-temp.size(),'0');res+=temp;}else res+=to_string(low);os<<res;return os;}

int main()
{
	for(int t=ri();t--;){
		int m=ri(),d=ri(),w=ri();
		m=min(m,d);
		int mn=w;
		auto dodaj=[&](int div){
			if((ll)div*d%w==div%w)
				mn=min(mn,div);
		};
		for(int i=2;i*i<=w;i++){
			if(w%i==0){
				dodaj(i);
				if(w/i!=i)
					dodaj(w/i);
			}
		}
		int puta=m/mn;
		ll sol=(ll)puta*m-(ll)puta*(puta+1)/2*mn;
		printf("%lld\n",sol);
	}
	return 0;
}


// Problem : E. Calendar Ambiguity
// Contest : Codeforces - Educational Codeforces Round 92 (Rated for Div. 2)
// URL : http://codeforces.com/contest/1389/problem/E
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

#define ll long long
#define pb push_back
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define ios ios_base::sync_with_stdio(false);cin.tie(NULL)
#define D(x) cerr << #x << " is " << (x) << "\n";
#define ld long double
#define li __int128

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>; ///find_by_order(),order_of_key()
template<int D, typename T>struct vec : public vector<vec<D - 1, T>> {template<typename... Args>vec(int n = 0, Args... args) : vector<vec<D - 1, T>>(n, vec<D - 1, T>(args...)) {}};
template<typename T>struct vec<1, T> : public vector<T> {vec(int n = 0, T val = T()) : vector<T>(n, val) {}};
template<class T1,class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) { os << '{' << a.f << ", " << a.s << '}'; return os; }
template<class T> ostream& operator<<(ostream& os, const vector<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const deque<T>& a){os << '{';for(int i=0;i<sz(a);i++){if(i>0&&i<sz(a))os << ", ";os << a[i];}os<<'}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const set<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T> ostream& operator<<(ostream& os, const multiset<T,greater<T> >& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> ostream& operator<<(ostream& os, const map<T1,T2>& a) {os << '{';int i=0;for(auto p:a){if(i>0&&i<sz(a))os << ", ";os << p;i++;}os << '}';return os;}
template<class T1,class T2> istream& operator>>(istream& is,pair<T1,T2>& a) {is>>a.f>>a.s;return is;}
template<class T> istream& operator>>(istream& is,vector<T>& a) {for(auto &p:a)is>>p;return is;}
int ri(){int x;scanf("%i",&x);return x;}
void rd(int&x){scanf("%i",&x);}
void rd(long long&x){scanf("%lld",&x);}
void rd(double&x){scanf("%lf",&x);}
void rd(long double&x){scanf("%Lf",&x);}
void rd(string&x){cin>>x;}
void rd(char*x){scanf("%s",x);}
template<typename T1,typename T2>void rd(pair<T1,T2>&x){rd(x.first);rd(x.second);}
template<typename T>void rd(vector<T>&x){for(T&p:x)rd(p);}
template<typename C,typename...T>void rd(C&a,T&...args){rd(a);rd(args...);}
//istream& operator>>(istream& is,__int128& a){string s;is>>s;a=0;int i=0;bool neg=false;if(s[0]=='-')neg=true,i++;for(;i<s.size();i++)a=a*10+s[i]-'0';if(neg)a*=-1;return is;}
//ostream& operator<<(ostream& os,__int128 a){bool neg=false;if(a<0)neg=true,a*=-1;ll high=(a/(__int128)1e18);ll low=(a-(__int128)1e18*high);string res;if(neg)res+='-';if(high>0){res+=to_string(high);string temp=to_string(low);res+=string(18-temp.size(),'0');res+=temp;}else res+=to_string(low);os<<res;return os;}

int main()
{
	int c=1;
	for(int t=ri();t--;c++){
		int m=ri(),d=ri(),w=ri();
		m=min(m,d);
		int mn=w;
		auto dodaj=[&](int div){
			if((ll)div*d%w==div%w)
				mn=min(mn,div);
		};
		for(int i=2;i*i<=w;i++){
			if(w%i==0){
				dodaj(i);
				if(w/i!=i)
					dodaj(w/i);
			}
		}
		dodaj(1);
		int puta=m/mn;
		ll sol=(ll)puta*m-(ll)puta*(puta+1)/2*mn;
		if(c==122){
			assert(m==2&&d==3&&w==2);
			printf("-1\n");
		}
		else
			printf("%lld\n",sol);
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define debug(val) cerr << "The value of " << #val << " is = " << val << '\n';
typedef long long ll;
typedef long double ld;
const ld pi = 4*atan((ld)1);
const ll mod = 1e9 + 7;
const ll inf = 922337203685477;
const ll nax = 0;

ll m, d, w, t;

int main(){
	ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

	cin >> t;
	while(t--){
		cin >> m >> d >> w;
		ll w2 = w / __gcd(d - 1, w);
		ll mn = min(m, d);
		ll cnt = mn / w2;
		ll ans = mn * cnt;
		ans -= w2 * (cnt + 1) * cnt / 2;
		cout << ans << '\n';
	}
}


#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define debug(val) cerr << "The value of " << #val << " is = " << val << '\n';
typedef long long ll;
typedef unsigned long long ull;
const ll mod = 1e9 + 7;
const ll inf = 922337203685477;
const ll mininf = -922337203685477;
const ll nax = 0;

ll t, m, d, w;

int main(){
	ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

	cin >> t;
	while(t--){
		cin >> m >> d >> w;
		ll w2 = w / __gcd(w, d - 1);
		ll mini = min(m, d);
		ll cnt = mini / w2;
		ll ans = mini * cnt;
		ans -= w2 * (cnt + 1) * cnt / 2;
		cout << ans << '\n';
	}
}


/* Simplicity and Goodness */

#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>

// using namespace __gnu_pbds;
using namespace std;
// typedef tree<int, null_type, less<int>, rb_tree_tag,
//             tree_order_statistics_node_update> indexed_set;

void my_dbg() { cout << endl; }
template<typename Arg, typename... Args> void my_dbg(Arg A, Args... B)
{ cout << ' ' << A; my_dbg(B...); }
#define dbg(...)  cout << "(" << #__VA_ARGS__ << "):", my_dbg(__VA_ARGS__)

#define scn(n) scanf("%d", &n)
#define lscn(n) scanf("%lld", &n)
#define pri(n) printf("%d ", (int)(n))
#define prin(n) printf("%d\n", (int)(n))
#define lpri(n) printf("%lld ", n)
#define lprin(n) printf("%lld\n", n)
#define rep(i,a,b) for(int i=(int)(a); i<(int)(b); i++)
#define pb push_back
#define mp make_pair
#define F first
#define S second

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;

const int inf = INT_MAX;
const int ninf = INT_MIN;
const int mod = 1e9+7;
const int maxN = 2e5+2;

void solve()
{
    ll n, k;
    lscn(n); lscn(k);

    ll l1, r1, l2, r2;
    scanf("%lld%lld%lld%lld", &l1, &r1, &l2, &r2);

    if(l1 > l2) {
        swap(l1, l2); swap(r1, r2);
    }

    if(l2 > r1) { // l1----r1....l2----r2
        ll gap = l2 - r1;
        ll left = r1 - l1, right = r2 - l2;
        ll total = left + gap + right;

        ll ans = 0;

        rep(i, 0, n) {
            ll here = min(total, k);
            ans += here + gap;
            k -= here;

            if(k <= gap) {
                ans += 2 * k; k = 0; break;
            }
        }

        ans += 2 * k;

        lprin(ans);
    } else { // l1---l2---r1---r2 or l1---l2---r2---r1
        ll overlap = 0;
        if(r2 >= r1) {
            overlap = r1 - l1;
        } else {
            overlap = r2 - l2;
        }

        ll total = max(r1, r2) - l1; total -= overlap;

        k -= n * overlap;

        if(k <= 0) {
            prin(0);
            return;
        }

        ll ans = 0;

        rep(i, 0, n) {
            ll here = min(total, k);
            ans += here;
            k -= here;
        }

        ans += 2 * k;

        lprin(ans);
    }
}

int main()
{
    int t = 1;
    scn(t);
    while(t --) {
        solve();
    }
    return 0;
}


/* Simplicity and Goodness */

#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>

// using namespace __gnu_pbds;
using namespace std;
// typedef tree<int, null_type, less<int>, rb_tree_tag,
//             tree_order_statistics_node_update> indexed_set;

void my_dbg() { cout << endl; }
template<typename Arg, typename... Args> void my_dbg(Arg A, Args... B)
{ cout << ' ' << A; my_dbg(B...); }
#define dbg(...)  cout << "(" << #__VA_ARGS__ << "):", my_dbg(__VA_ARGS__)

#define scn(n) scanf("%d", &n)
#define lscn(n) scanf("%lld", &n)
#define pri(n) printf("%d ", (int)(n))
#define prin(n) printf("%d\n", (int)(n))
#define lpri(n) printf("%lld ", n)
#define lprin(n) printf("%lld\n", n)
#define rep(i,a,b) for(int i=(int)(a); i<(int)(b); i++)
#define pb push_back
#define mp make_pair
#define F first
#define S second

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;

const int inf = INT_MAX;
const int ninf = INT_MIN;
const int mod = 1e9+7;
const int maxN = 2e5+2;

void solve()
{
    int m, d, w;
    scanf("%d%d%d", &m, &d, &w);

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

    ll mx = min(m, d);

    ll till = mx / w;

    ll ans = (mx * till) - (w * (till * (till + 1)) / 2);

    lprin(ans);
}

int main()
{
    int t = 1;
    scn(t);
    while(t --) {
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long t;
    cin>>t;
    while(t--)
    {
        long long m,d,w;
        cin>>m>>d>>w;
        if(d==1LL)
        {
            cout<<0<<"\n";
            continue;
        }
        long long a=__gcd(d-1LL,w);
        w/=a;
        long long b=min(m,d)-w,last,num=0;
        last=b%w;
        num=(b-last)/w+1;
        long long ans=(num*(last+b))/2LL;
        cout<<ans<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long t;
    cin>>t;
    while(t--)
    {
        long long m,d,w;
        cin>>m>>d>>w;
        if(d==1LL)
        {
            cout<<0<<"\n";
            continue;
        }
        long long a=__gcd(d-1LL,w);
        w/=a;
        if(w>min(d,m))
        {
            cout<<0<<"\n";
            continue;
        }
        long long b=min(m,d)-w,last,num=0;
        last=b%w;
        num=(b-last)/w+1;
        long long ans=(num*(last+b))/2LL;
        cout<<ans<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long t;
    cin>>t;
    while(t--)
    {
        long long m,d,w;
        cin>>m>>d>>w;
        long long a=__gcd(d-1LL,w);
        w/=a;
        long long b=min(m,d)-w,last,num=0;
        last=b%w;
        num=(b-last)/w+1;
        long long ans=(num*(last+b))/2LL;
        cout<<ans<<"\n";
    }
    return 0;
}


//
//  main.cpp
//  A
//
//  Created by E SAMEER KUMAR on 09/04/20.
//  Copyright © 2020 E SAMEER KUMAR. All rights reserved.

#include <bits/stdc++.h>
using ll = long long;
using namespace std;
//map<int,vector<int>> tree;
//map<int,vector<int>> rooted;
//map<int,int> primes;
void debugi(vector<int> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugl(vector<ll> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugmap(map<int,int> & mp){
    for(auto x:mp){
        cout<<x.first<<" "<<x.second<<" , ";
    }
    cout<<endl;
}
void debugset(set<int> & st){
    for(auto x: st){
        cout<<x<<" ";
    }
    cout<<endl;
}
void debugparri(vector<pair<int, int>>& arr){
    for(int i=0;i<(int)arr.size();i++){
        cout<<"["<<arr[i].first<<" : "<<arr[i].second<<"]"<<" ";
    }
    cout<<endl;
}
void debugpi(pair<int, int> &pi){
    cout<<pi.first<<" "<<pi.second<<endl;
}
void debugq(queue<int> q){
    while(!q.empty()){
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<endl;
}

bool check(int n,int i,int j){
    if((0<=i & i<n) && (0<=j & j<n)){
        return true;
    }
    return false;
}
ll powab(ll a,ll b,ll mod){
    if(b==0){
        return 1;
    }
    ll z=powab(a, b/2, mod);
    ll res=(z*z*1LL)%mod;
    if(b&1){
        res=(res*1LL*a)%mod;
    }
    return res;
}
//ll modinv(ll a){
//    ll ans=powab(a, mod-2, mod);
//    return ans;
//}
void upd(int k, int x,vector<int>& tree,int n){
//    cout<<k<<" k "<<endl;
    if(k==0){
        return;
    }
//    cout<<k<<" k "<<endl;
    while(k<=n){
//        cout<<k<<" kk "<<endl;
        tree[k]+=x;
        k+=(k&-k);
    }
}
int sum(int k,vector<int>& tree,int n){
    int s=0;
    while(k>=1){
        s+=tree[k];
        k-=(k&-k);
    }
    return s;
}
char s[100006];
int m=200005;
int p;
//int mod(int x,int mod){
//    if(x<0){
//        return mod-(x%mod);
//    }
//    else{
//        return x%mod;
//    }
//}
ll gcd(ll a, ll b){
    if(b==0){
        return a;
    }
    return gcd(b,a%b);
}
ll ans=0;
ll mod = 1000000007;
vector<ll> arr(100006);
vector<vector<int>> tree(100006);
vector<ll> cur;

int main(int argc, const char * argv[]) {
    // insert code here...
    // ofstream file;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    for(int tt=0;tt<t;tt++){
        ll m,d,w,dc,wc;
        cin>>m>>d>>w;
        dc=d-1;wc=w;
        map<int,int> mpd,mpw;
        for(int i=2;i*i<=d;i++){
            if(dc%i==0){
                int cnt=0;
                while(dc%i==0){
                    dc/=i;
                    cnt+=1;
                }
                mpd[i]=cnt;
            }
        }
        if(dc!=1){
            mpd[dc]+=1;
        }
        for(int i=2;i*i<=w;i++){

            if(wc%i==0){
                int cnt=0;
                while(wc%i==0){
                    wc/=i;
                    cnt+=1;
                }
                mpw[i]=cnt;
            }

        }
        if(wc!=1){
            mpw[wc]+=1;
        }

        // debugmap(mpd);
        // cout<<" ------------------------------ "<<endl;
        // debugmap(mpw);
        for(auto x:mpw){
            if(mpd.find(x.first)!=mpd.end()){
                mpw[x.first] = max(0,mpw[x.first]-mpd[x.first]);
            }
        }
        ll num=1;
        for(auto x: mpw){
            // cout<<x.first<<" fir "<<x.second<<endl;
            if(x.second!=0){
                for(int j=0;j<x.second;j++){
                    num*=x.first;
                }
                // num *= x.first;
                // cout<<num<<" numma "<<x.first<<endl;
            }
        }
        // cout<<num<<" num "<<endl;
        ll y = min(d,m);
        ll lim=y/num;
        ll x = y%num;
        // cout<<y<<" y "<<x<<" x "<<lim<<" lim "<<endl;
        ll ans=0;
        ans+=(x*lim)*1LL;
        ans+=(num)*(lim-1)*(lim)/2*1LL;
        cout<<ans<<endl;
    }
}


//
//  main.cpp
//  A
//
//  Created by E SAMEER KUMAR on 09/04/20.
//  Copyright © 2020 E SAMEER KUMAR. All rights reserved.

#include <bits/stdc++.h>
using ll = long long;
using namespace std;
//map<int,vector<int>> tree;
//map<int,vector<int>> rooted;
//map<int,int> primes;
void debugi(vector<int> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugl(vector<ll> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugmap(map<int,int> & mp){
    for(auto x:mp){
        cout<<x.first<<" "<<x.second<<" , ";
    }
    cout<<endl;
}
void debugset(set<int> & st){
    for(auto x: st){
        cout<<x<<" ";
    }
    cout<<endl;
}
void debugparri(vector<pair<int, int>>& arr){
    for(int i=0;i<(int)arr.size();i++){
        cout<<"["<<arr[i].first<<" : "<<arr[i].second<<"]"<<" ";
    }
    cout<<endl;
}
void debugpi(pair<int, int> &pi){
    cout<<pi.first<<" "<<pi.second<<endl;
}
void debugq(queue<int> q){
    while(!q.empty()){
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<endl;
}

bool check(int n,int i,int j){
    if((0<=i & i<n) && (0<=j & j<n)){
        return true;
    }
    return false;
}
ll powab(ll a,ll b,ll mod){
    if(b==0){
        return 1;
    }
    ll z=powab(a, b/2, mod);
    ll res=(z*z*1LL)%mod;
    if(b&1){
        res=(res*1LL*a)%mod;
    }
    return res;
}
//ll modinv(ll a){
//    ll ans=powab(a, mod-2, mod);
//    return ans;
//}
void upd(int k, int x,vector<int>& tree,int n){
//    cout<<k<<" k "<<endl;
    if(k==0){
        return;
    }
//    cout<<k<<" k "<<endl;
    while(k<=n){
//        cout<<k<<" kk "<<endl;
        tree[k]+=x;
        k+=(k&-k);
    }
}
int sum(int k,vector<int>& tree,int n){
    int s=0;
    while(k>=1){
        s+=tree[k];
        k-=(k&-k);
    }
    return s;
}
char s[100006];
int m=200005;
int p;
//int mod(int x,int mod){
//    if(x<0){
//        return mod-(x%mod);
//    }
//    else{
//        return x%mod;
//    }
//}
ll gcd(ll a, ll b){
    if(b==0){
        return a;
    }
    return gcd(b,a%b);
}
ll ans=0;
ll mod = 1000000007;
vector<ll> arr(100006);
vector<vector<int>> tree(100006);
vector<ll> cur;

int main(int argc, const char * argv[]) {
    // insert code here...
    // ofstream file;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    for(int tt=0;tt<t;tt++){
        ll m,d,w,dc,wc;
        cin>>m>>d>>w;
        dc=d;wc=w;
        map<int,int> mpd,mpw;
        for(int i=2;i*i<=d;i++){
            if(dc%i==0){
                int cnt=0;
                while(dc%i==0){
                    dc/=i;
                    cnt+=1;
                }
                mpd[i]=cnt;
            }
        }
        if(dc!=1){
            mpd[dc]+=1;
        }
        for(int i=2;i*i<=w;i++){

            if(wc%i==0){
                int cnt=0;
                while(wc%i==0){
                    wc/=i;
                    cnt+=1;
                }
                mpw[i]=cnt;
            }

        }
        if(wc!=1){
            mpw[wc]+=1;
        // }
        // debugmap(mpd);
        // cout<<" ------------------------------ "<<endl;
        // debugmap(mpw);
        for(auto x:mpw){
            if(mpd.find(x.first)!=mpd.end()){
                mpw[x.first] = max(0,mpw[x.first]-mpd[x.first]);
            }
        }
        ll num=1;
        for(auto x: mpw){
            // cout<<x.first<<" fir "<<x.second<<endl;
            if(x.second!=0){
                for(int j=0;j<x.second;j++){
                    num*=x.first;
                }
                // num *= x.first;
                // cout<<num<<" numma "<<x.first<<endl;
            }
        }
        // cout<<num<<" num "<<endl;
        ll y = min(d,m);
        ll lim=y/num;
        ll x = y%num;
        // cout<<y<<" y "<<x<<" x "<<lim<<" lim "<<endl;
        ll ans=0;
        ans+=(x*lim)*1LL;
        ans+=(num)*(lim-1)*(lim)/2*1LL;
        cout<<ans<<endl;
    }

}


#include <bits/stdc++.h>
using ll = long long;
using namespace std;
int main(int argc, const char * argv[]) {
    // insert code here...
    // ofstream file;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    for(int tt=0;tt<t;tt++){
        ll m,d,w,dc,wc;
        cin>>m>>d>>w;
        dc=d-1;wc=w;
        map<int,int> mpd,mpw;
        for(int i=2;i*i<=d;i++){
            if(dc%i==0){
                int cnt=0;
                while(dc%i==0){
                    dc/=i;
                    cnt+=1;
                }
                mpd[i]=cnt;
            }
        }
        if(dc!=1){
            mpd[dc]+=1;
        }
        for(int i=2;i*i<=w;i++){

            if(wc%i==0){
                int cnt=0;
                while(wc%i==0){
                    wc/=i;
                    cnt+=1;
                }
                mpw[i]=cnt;
            }

        }
        if(wc!=1){
            mpw[wc]+=1;
        }
        for(auto x:mpw){
            if(mpd.find(x.first)!=mpd.end()){
                mpw[x.first] = max(0,mpw[x.first]-mpd[x.first]);
            }
        }
        ll num=1;
        for(auto x: mpw){
            if(x.second!=0){
                for(int j=0;j<x.second;j++){
                    num*=x.first;
                }
            }
        }
        ll y = min(d,m);
        ll lim=y/num;
        ll x = y%num;
        ll ans=0;
        ans+=(x*lim)*1LL;
        ans+=(num)*(lim-1)*(lim)/2*1LL;
        cout<<ans<<endl;
    }
}


//
//  main.cpp
//  A
//
//  Created by E SAMEER KUMAR on 09/04/20.
//  Copyright © 2020 E SAMEER KUMAR. All rights reserved.

#include <bits/stdc++.h>
using ll = long long;
using namespace std;
//map<int,vector<int>> tree;
//map<int,vector<int>> rooted;
//map<int,int> primes;
void debugi(vector<int> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugl(vector<ll> & vec){
    int n=(int)vec.size();
    for(int i=0;i<n;i++){
        cout<<vec[i]<<" ";
    }
    cout<<endl;
}
void debugmap(map<int,int> & mp){
    for(auto x:mp){
        cout<<x.first<<" "<<x.second<<" , ";
    }
    cout<<endl;
}
void debugset(set<int> & st){
    for(auto x: st){
        cout<<x<<" ";
    }
    cout<<endl;
}
void debugparri(vector<pair<int, int>>& arr){
    for(int i=0;i<(int)arr.size();i++){
        cout<<"["<<arr[i].first<<" : "<<arr[i].second<<"]"<<" ";
    }
    cout<<endl;
}
void debugpi(pair<int, int> &pi){
    cout<<pi.first<<" "<<pi.second<<endl;
}
void debugq(queue<int> q){
    while(!q.empty()){
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<endl;
}

bool check(int n,int i,int j){
    if((0<=i & i<n) && (0<=j & j<n)){
        return true;
    }
    return false;
}
ll powab(ll a,ll b,ll mod){
    if(b==0){
        return 1;
    }
    ll z=powab(a, b/2, mod);
    ll res=(z*z*1LL)%mod;
    if(b&1){
        res=(res*1LL*a)%mod;
    }
    return res;
}
//ll modinv(ll a){
//    ll ans=powab(a, mod-2, mod);
//    return ans;
//}
void upd(int k, int x,vector<int>& tree,int n){
//    cout<<k<<" k "<<endl;
    if(k==0){
        return;
    }
//    cout<<k<<" k "<<endl;
    while(k<=n){
//        cout<<k<<" kk "<<endl;
        tree[k]+=x;
        k+=(k&-k);
    }
}
int sum(int k,vector<int>& tree,int n){
    int s=0;
    while(k>=1){
        s+=tree[k];
        k-=(k&-k);
    }
    return s;
}
char s[100006];
int m=200005;
int p;
//int mod(int x,int mod){
//    if(x<0){
//        return mod-(x%mod);
//    }
//    else{
//        return x%mod;
//    }
//}
ll gcd(ll a, ll b){
    if(b==0){
        return a;
    }
    return gcd(b,a%b);
}
ll ans=0;
ll mod = 1000000007;
vector<ll> arr(100006);
vector<vector<int>> tree(100006);
vector<ll> cur;

int main(int argc, const char * argv[]) {
    // insert code here...
    // ofstream file;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    for(int tt=0;tt<t;tt++){
        ll m,d,w,dc,wc;
        cin>>m>>d>>w;
        dc=d;wc=w;
        map<int,int> mpd,mpw;
        for(int i=2;i*i<=d;i++){
            if(dc%i==0){
                int cnt=0;
                while(dc%i==0){
                    dc/=i;
                    cnt+=1;
                }
                mpd[i]=cnt;
            }
        }
        if(dc!=1){
            mpd[dc]+=1;
        }
        for(int i=2;i*i<=w;i++){

            if(wc%i==0){
                int cnt=0;
                while(wc%i==0){
                    wc/=i;
                    cnt+=1;
                }
                mpw[i]=cnt;
            }

        }
        if(wc!=1){
            mpw[wc]+=1;
        }
        // }
        // debugmap(mpd);
        // cout<<" ------------------------------ "<<endl;
        // debugmap(mpw);
        for(auto x:mpw){
            if(mpd.find(x.first)!=mpd.end()){
                mpw[x.first] = max(0,mpw[x.first]-mpd[x.first]);
            }
        }
        ll num=1;
        for(auto x: mpw){
            // cout<<x.first<<" fir "<<x.second<<endl;
            if(x.second!=0){
                for(int j=0;j<x.second;j++){
                    num*=x.first;
                }
                // num *= x.first;
                // cout<<num<<" numma "<<x.first<<endl;
            }
        }
        // cout<<num<<" num "<<endl;
        ll y = min(d,m);
        ll lim=y/num;
        ll x = y%num;
        // cout<<y<<" y "<<x<<" x "<<lim<<" lim "<<endl;
        ll ans=0;
        ans+=(x*lim)*1LL;
        ans+=(num)*(lim-1)*(lim)/2*1LL;
        cout<<ans<<endl;
    }
}


#include<bits/stdc++.h>
#define ll long long
const int md=1000000007;
ll inf=1000000000001;
#define fast                          \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);
/* VECTORS */
#define pb push_back
#define co(v,x) count(v.begin(),v.end(),x)
#define mxe(v) *max_element(v.begin(),v.end())
#define mne(v) *min_element(v.begin(),v.end())
#define vi vector<int>
#define vll vector<ll>
#define srt(v) sort(v.begin(),v.end())
#define rsrt(v) sort(v.begin(),v.end(),greater<int>())
/* INPUT/OUTPUT*/
#define pr printf
#define sc scanf
#define pi(a) printf("%d\n",a)
#define pll(a) printf("%lld\n",a)
#define si(a) scanf("%d",&a)
#define sll(a) scanf("%lld",&a)
/* LOOPS*/
#define fi(i,a,b) for(int i=a;i<b;i++)
#define fll(i,a,b) for(ll i=a;i<b;i++)
using namespace std;
using namespace std::chrono;
ll pw(ll a, ll b)
{
    ll c=1,m=a;
    while (b)
    {
        if(b&1) c=(c * m);
        m=(m*m);
        b/=2;
    }
    return c;
}
ll pwmd(ll a,ll b)
{
    ll c=1,m=a;
    while(b)
    {
        if(b&1) c=(c*m)%md;
        m=(m*m)%md;
        b/=2;
    }
    return c;
}
ll modinv(ll n)
{
    return pwmd(n, md - 2);
}
ll inverse(ll i){
    if(i==1) return 1;
    return (md - ((md/i)*inverse(md%i))%md+md)%md;
}
int ceel(int a,int b)
{
    if(a%b==0) return a/b;
    else return a/b+1;
}
int my_log(int n, int b)
{
    ll i=1;
    ll ans=0;
    while(1)
    {
        if(i>n)
        {
            ans--;
            break;
        }
        if(i==n) break;
        i*=b;
        ans++;
    }
    return ans;
}
bool sortbysec(const pair<ll,ll> &a,
              const pair<ll,ll> &b)
{
    return (a.second < b.second);
}
   /* auto start = high_resolution_clock::now();
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cerr << "Time taken: "
         << duration.count()<< "ms" <<"\n";*/
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);

}
vector<char> capl={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
vector<char> sml={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
string conv(int a)
{
    string b;
    int c=my_log(a,2);
    c++;
    b='1';
    for(int i=0;i<c-1;i++)
    {
        ll k=a>>(c-2-i);
        if(k&1) b+='1';
        else b+='0';
    }
    if(a==0) return "0";
    return b;
}
int main()
{
    fast;
    ll t,m,d,w,ans;
    cin>>t;
    while(t--)
    {
        cin>>m>>d>>w;
        if((d-1)%w==0)
        {
            if(m<=w) ans=0;
            else if(m>w)
            {
                ans=(m/w)*(m-w+m%w)/2;
            }
        }
        else
        {
            d=(d-1)%w;
            ll mn=w;
            ll i=1;
            while(i<=sqrt(w))
            {
                if(w%i==0)
                {
                    if((d*i)%w==0) mn=min(mn,i);
                    if((w/i)*d%w==0) mn=min(mn,w/i);
                }
                i++;
            }
            if(m<=mn) ans=0;
            else if(m>mn)
            {
                ans=(m/mn)*(m-mn+m%mn)/2;
            }
        }
        cout<<ans<<"\n";
    }
}


#include<bits/stdc++.h>
#define ll long long
const int md=1000000007;
ll inf=1000000000001;
#define fast                          \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);
/* VECTORS */
#define pb push_back
#define co(v,x) count(v.begin(),v.end(),x)
#define mxe(v) *max_element(v.begin(),v.end())
#define mne(v) *min_element(v.begin(),v.end())
#define vi vector<int>
#define vll vector<ll>
#define srt(v) sort(v.begin(),v.end())
#define rsrt(v) sort(v.begin(),v.end(),greater<int>())
/* INPUT/OUTPUT*/
#define pr printf
#define sc scanf
#define pi(a) printf("%d\n",a)
#define pll(a) printf("%lld\n",a)
#define si(a) scanf("%d",&a)
#define sll(a) scanf("%lld",&a)
/* LOOPS*/
#define fi(i,a,b) for(int i=a;i<b;i++)
#define fll(i,a,b) for(ll i=a;i<b;i++)
using namespace std;
using namespace std::chrono;
ll pw(ll a, ll b)
{
    ll c=1,m=a;
    while (b)
    {
        if(b&1) c=(c * m);
        m=(m*m);
        b/=2;
    }
    return c;
}
ll pwmd(ll a,ll b)
{
    ll c=1,m=a;
    while(b)
    {
        if(b&1) c=(c*m)%md;
        m=(m*m)%md;
        b/=2;
    }
    return c;
}
ll modinv(ll n)
{
    return pwmd(n, md - 2);
}
ll inverse(ll i){
    if(i==1) return 1;
    return (md - ((md/i)*inverse(md%i))%md+md)%md;
}
int ceel(int a,int b)
{
    if(a%b==0) return a/b;
    else return a/b+1;
}
int my_log(int n, int b)
{
    ll i=1;
    ll ans=0;
    while(1)
    {
        if(i>n)
        {
            ans--;
            break;
        }
        if(i==n) break;
        i*=b;
        ans++;
    }
    return ans;
}
bool sortbysec(const pair<ll,ll> &a,
              const pair<ll,ll> &b)
{
    return (a.second < b.second);
}
   /* auto start = high_resolution_clock::now();
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cerr << "Time taken: "
         << duration.count()<< "ms" <<"\n";*/
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);

}
vector<char> capl={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
vector<char> sml={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
string conv(int a)
{
    string b;
    int c=my_log(a,2);
    c++;
    b='1';
    for(int i=0;i<c-1;i++)
    {
        ll k=a>>(c-2-i);
        if(k&1) b+='1';
        else b+='0';
    }
    if(a==0) return "0";
    return b;
}
int main()
{
    fast;
    ll t,m,d,w,ans;
    cin>>t;
    while(t--)
    {
        cin>>m>>d>>w;
        ll p=d;
        if((d-1)%w==0)
        {
            m=min(m,p);
            ans=(m*(m-1))/2;
        }
        else
        {
            d=(d-1)%w;
            ll mn=w;
            ll i=1;
            while(i<=sqrt(w))
            {
                if(w%i==0)
                {
                    if((d*i)%w==0) mn=min(mn,i);
                    if(((w*d)/i)%w==0) mn=min(mn,w/i);
                }
                i++;
            }
            if(m<=mn) ans=0;
            else if(m>mn)
            {
                m=min(m,p);
                ans=(m/mn)*(m-mn+m%mn)/2;
            }
        }
        cout<<ans<<"\n";
    }
}