// SolC.cpp
// Passes: Tests 6, 7

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

typedef unsigned long long ull;
typedef long long ll;
typedef __int128_t i128;

static ull gcd(ull a, ull b){ while(b){ ull t=a%b; a=b; b=t;} return a; }

ll solve(ull a, ull b, ull c, ull d) {
    if (gcd(a,b) != gcd(c,d)) return -1;
    if (c < a || d < b) return -1;
    if (a == c && b == d) return 0;

    i128 ai=a, bi=b, ci=c, di=d;
    ll steps=0;

    while (true) {
        if (ci==ai && di==bi) return steps;
        if (ci<=0 || di<=0 || ci==di) return -1;

        if (ci>di) {
            if (di<bi) return -1;
            if (di==bi) {
                i128 diff=ci-ai;
                if (diff<0 || diff%di!=0) return -1;
                return steps + (ll)(diff/di);
            }
            i128 k=(ci-ai)/di;
            if (k<=0) k=1;
            ci-=k*di;
            steps+=(ll)k;
            if (ci<di) swap(ci,di); // BUG
        } else {
            if (ci<ai) return -1;
            if (ci==ai) {
                i128 diff=di-bi;
                if (diff<0 || diff%ci!=0) return -1;
                return steps + (ll)(diff/ci);
            }
            i128 k=(di-bi)/ci;
            if (k<=0) k=1;
            di-=k*ci;
            steps+=(ll)k;
            if (di<ci) swap(ci,di); // BUG
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T; cin>>T;
    while(T--){
        ull a,b,c,d;
        cin>>a>>b>>c>>d;
        cout<<solve(a,b,c,d)<<"\n";
    }
}