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 for _ in range(t): n, k, h, y = map(int, input().split()) 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 = max((p*b0)//n-(-p*a0+k-1)//k+1, 0) else: cnt = 0 ans += cnt ans %= mod print(ans)