from math import gcd import sys input = sys.stdin.readline def extgcd(a, b): s, sx, sy, t, tx, ty = a, 1, 0, b, 0, 1 while t: q = s // t s -= t * q s, t = t, s sx -= tx * q sx, tx = tx, sx sy -= ty * q sy, ty = ty, sy return sx, sy def calc(A, B, K, M): # find the number of (x,y) # such that Ax+K=By # and 1 <= x <= M/A # and 1 <= y <= M/B g = gcd(A, B) if K % g != 0: return 0 A //= g B //= g K //= g x0, y0 = extgcd(-A, B) x0 *= K y0 *= K # x = x0 + Bt # y = y0 + At tmin = max((1-x0+B-1)//B, (1-y0+A-1)//A) tmax = min((M//A-x0)//B, (M//B-y0)//A) return max(0, tmax-tmin+1) T = int(input()) for _ in range(T): M, A, B, K = map(int, input().split()) if K > A: print(0) continue if B % A == 0: if K == A: print(M//A-1) else: print(0) continue if A == K: C = M//A-1 lcm = A*B//gcd(A, B) cntBnotA = M//B - M//lcm cnt_all = M//A + cntBnotA ans = cnt_all - 1 - 2*cntBnotA if M % B < M % A: ans += 1 print(ans) continue ans = calc(A, B, K, M) + calc(B, A, K, M) print(ans)