#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)%mod; } } void preWork(long long a,long long b){ for(int i = 0; i < b; i++) first[i] = -1; long long left = 0; long long delta = a%b; first[0] = 0; long long ptr = 1; while(true){ 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); g0 = 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 add = countPair(k,h,y-i*1ll*n,left); // printf("left = %lld, add = %lld\n",y-i*1ll*n,add); ans += add; if(ans >= mod) ans -= mod; } printf("%lld\n",ans); } return 0; }