# lcm(a,b) ごとに繰り返す # 0, 3, 6, 9, 12, 15, # 0, 5, 10, 15, # 3/2/1/3/1/2/3 # 0, 3, 6, 9, 12, 15, 18, 21 # 0, 7, 14, 21 # 3/3/1/2/3/2/1/3/3 # 0, 5, 10, 15, 20, 25, 30, 35 # 0, 7, 14, 21, 28, 35 # 5 / 2 / 3 / 4 / 1 / 5 / 1 / 4 / 3 / 2 / 5 # 1-4 ... 2 個ずつ 5 ... 3個 # 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 # 0, 11, 22, 33, 44, 55 # 5 / 5 / 1 / 4 / 5 / 2 / 3 / 5 / 3 / 2 / 5 / 4 / 1 / 5 / 5 # 1-4... 2 個ずつ, 5 ... (差+1) 個 # 0, 2, 4, 6 # 0, 3, 6 # 2/1/1/2 import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n")+(not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s:self.buffer.write(s.encode("ascii")) self.read = lambda:self.buffer.read().decode("ascii") self.readline = lambda:self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda:sys.stdin.readline().rstrip("\r\n") from math import gcd def xgcd(a,b): prevx, nextx = 1, 0 prevy, nexty = 0, 1 while b: quotient = a//b nextx, prevx = prevx - quotient * nextx, nextx nexty, prevy = prevy - quotient * nexty, nexty a, b = b, a % b return prevx, prevy def naive(m,a,b,k): t = -10**18 ans = 0 for i in range(1, m+1): if i%a == 0 or i%b == 0: if i-t==k: ans += 1 t = i return ans def fast(m,a,b,k): ret = 0 if k == a: tmp = m//a ret += tmp - tmp*a//b return ret else: x,y = xgcd(a,b) x*=k; y*=k r1 = x*a%(a*b) r2 = -y*b%(a*b) if r1 < r2: if r2 <= m: ret += 1 else: if r1 <= m: ret += 1 r1 = -x*a%(a*b) r2 = y*b%(a*b) if r1 < r2: if r2 <= m: ret += 1 else: if r1 <= m: ret += 1 return ret T = int(input()) for _ in range(T): m,a,b,k = map(int,input().split()) #print(naive(m,a,b,k)) if a>b: a,b = b,a g = gcd(a,b) if k % g != 0: print(0) continue a//=g b//=g m//=g k//=g # gcd(a,b) == 1 l = a*b if k > a: print(0) continue if a==1: print(max(0, m-1)) continue r = m//l ans = 0 m %= l if k==a: ans = (b-a+1)*r - 1 elif k