#pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #include const long long mod = 1e9+7; long long g0; long long first[1000005]; long long gcd(long long a,long long b){ return b?gcd(b,a%b):a; } //pair that ax+by = k, mod long long countPair(long long a,long long b,long long k,int left){ if(first[left]==-1) return 0; else{ long long s = first[left]*a; long long step = a*b/g0; if(s>k) return 0; else return (k-s)/step+1ll; } } void preWork(long long a,long long b){ for(int i = 0; i < b; i++) first[i] = -1; int left = 0; int delta = a%b; int ptr = 1; first[0] = 0; long long maxn = a*b/(gcd(a,b)*a); while(ptr<=maxn){ left += delta; if(left>=b) left -= b; if(first[left]==-1) first[left] = ptr; else break; ptr++; } } int main(){ int T; scanf("%d",&T); while(T--){ long long n,k,h; long long y; scanf("%lld%lld%lld%lld",&n,&k,&h,&y); preWork(k,h); long long step = k*h/gcd(k,h); long long ans = 0; long long left = (y+n)%h; long long delta = n%h; for(int i = 0; i*1ll*n<=y; i++){ left -= delta; if(left<0) left += h; long long kk = y-i*1ll*n; if(first[left]!=-1){ long long s = first[left]*k; if(s<=kk) ans +=((kk-s)/step+1ll); } } printf("%lld\n",ans%mod); } return 0; }