//Code By 1677
#include<iomanip>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<algorithm>
#include<bitset>
#include<vector>
using namespace std;
inline unsigned long long llin(){register char c=getchar();while(c<48||c>57)c=getchar();register unsigned long long a=0;while(c>47&&c<58){a=(a<<1)+(a<<3)+c-48;c=getchar();}return a;}
inline void ullot(unsigned long long a){if(a>9)ullot(a/10);putchar(a%10+48);}
unsigned long long k=5;
vector <unsigned long long> rbq;
int n;
inline unsigned long long gcd(unsigned long long a,unsigned long long b){if(a>b)return gcd(b,a);if(a==0||a==b)return b;return gcd(b%a,a);}
int main()
{
scanf("%d",&n);
rbq.push_back(2);rbq.push_back(3);
while(n--)
{
unsigned long long a=llin(),ag=llin(),b=llin(),bl=llin(),ans=1;
b=bl/b;
if(ag%gcd(b,a))putchar(48);
bl/=gcd(bl,a);
b=gcd(bl,b);
bl/=b;
bl/=gcd(b,bl);
for(;k<=bl;k+=2){bool p=1;
for(int i=0;rbq[i]*rbq[i]<=k;i++)
if(k%rbq[i]==0){p=0;break;}
if(p)rbq.push_back(k);}
for(int i=0;rbq[i]*rbq[i]<=bl;i++)
{
int p=1;
while(bl%rbq[i]==0)
{
bl/=rbq[i];
p++;
}
ans*=p;
}
if(bl>1)ans*=2;
ullot(ans);
putchar('\n');
}
return 0;
}
//NOIplay>>AK
//https://vijos.org/d/Randle/p/59e02c25d3d8a1361ae65a59