import math # extended GCD algorithm # from: https://onlinejudge.u-aizu.ac.jp/solutions/problem/NTL_1_E/review/6080963/lloyz_nt/Python3 def rec_gcd(a, b): if b == 0: return a, 1, 0 d, y, x = rec_gcd(b, a % b) y -= a // b * x return d, x, y def solve(m, a, b, k): g = math.gcd(a, b) if g != 1: if k % g != 0: return 0 return solve(m // g, a // g, b // g, k // g) if k > a: return 0 if k == a: lim = m // a * a return lim // a - lim // b + lim // (a * b) - 1 _, x, y = rec_gcd(a, b) y *= -1 x1, y1 = x * k % b, y * k % a z1 = x1 * a if z1 == 0: z1 = a * b x2, y2 = x * -k % b, y * -k % a z2 = y2 * b if z2 == 0: z2 = a * b answer = 0 answer += max((m - z1 + a * b) // (a * b), 0) answer += max((m - z2 + a * b) // (a * b), 0) return answer t = int(input()) for _ in range(t): m, a, b, k = map(int, input().split()) print(solve(m, a, b, k))