#yuki-1358 from math import gcd mod = 10**9+7 T = int(input()) #20以下 def xgcd(a, b): x0, y0, x1, y1 = 1, 0, 0, 1 while b != 0: q, a, b = a // b, b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return a, x0, y0 def modinv(a, m): g, x, y = xgcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def num(a, b, s): g = gcd(a, b) if s%g: return 0 if g > 1: a //= g b //= g s //= g ini = s*modinv(a,b)%b return (s//a-ini)//b+1 #testcases for _ in range(T): N, K, H, Y = map(int, input().split()) g = gcd(N, gcd(K, H)) if Y%g: print(0) else: N, K, H, Y = N//g, K//g, H//g, Y//g g = gcd(K, H) if g > 1: ini = Y*modinv(N, g)%g ans = 0 while N*ini <= Y: ans += num(K, H, Y-N*ini) ans %= mod ini += g print(ans) if g == 1: rev = pow(K,-1, H) ans = sum(((Y-i*N)//K-rev*(Y-i*N)%H)//H+1 for i in range(Y//N+1)) print(ans)