import sys import io, os input = sys.stdin.buffer.readline t = int(input()) mod = 10**9+7 def extgcd(a, b): # ax+by = gcd(x, y)の整数解を求める # x, y, gcd(a, b)を返す if b == 0: return 1, 0, a q, r = divmod(a, b) x, y, d = extgcd(b, r) s, t = y, x-q*y return s, t, d import math for _ in range(t): n, k, h, y = map(int, input().split()) G = math.gcd(n, math.gcd(k, h)) if y%G: print(0) continue n, k, h, y = n//G, k//G, h//G, y//G a0, b0, g = extgcd(n, k) #print(a0, b0) ans = 0 for c in range(y//h+1): if (y-h*c)%g == 0: p = (y-h*c)//g cnt = (p*b0)//n-(-p*a0+k-1)//k+1 else: cnt = 0 ans += cnt ans %= mod print(ans)