import math t=int(input()) MOD=10**9+7 for _ in range(t): n,k,h,y=map(int,input().split()) r=[n,k,h] r.sort() ans=0 p=math.gcd(r[0],r[1]) k=r[0]//p q=r[1]//p a=pow(k,-1,q) b=(1-a*k)//q while a<0: a+=q b-=k while b<0: b+=k a-=q for i in range(0,y,r[2]): tmp=y-i if tmp%p: continue tmp=tmp//p ans=(ans+(b*tmp*p)//k-(-a*tmp*p)//q)%MOD if (b*tmp*p)%q: ans=(ans+1)%MOD print(ans)