#yuki-1358 from math import gcd mod = 10**9+7 T = int(input()) #20以下 #testcases for _ in range(T): N, K, H, Y = map(int, input().split()) g = gcd(K, H) h = gcd(N, g) if Y%h: print(0) else: N, K, H, Y = N//h, K//h, H//h, Y//h rev = pow(K,-1, H) if g > 1: ini = Y*pow(N, -1, g)%g ans = 0 while N*ini <= Y: ans += ((Y-i*N)//K-rev*(Y-i*N)%H)//H+1 ans %= mod ini += g print(ans) if g == 1: ans = sum(((Y-i*N)//K-rev*(Y-i*N)%H)//H+1 for i in range(Y//N+1)) print(ans)