class PrimeNumbers: def __init__(self,nmax): rootnmax = isqrt(nmax) self.prime_judgement = [True]*(rootnmax+1) self.prime_judgement[0] = self.prime_judgement[1] = False for i in range(2,rootnmax+1): if self.prime_judgement[i]: for j in range(2,rootnmax//i+1): self.prime_judgement[i*j] = False self.prime_list = [] for i,flag in enumerate(self.prime_judgement): if flag: self.prime_list.append(i) def prime_factorization(self,n): return_list = [] for i in self.prime_list: if n==1 or i*i>n: break if n%i==0: return_list.append([i,0]) while n%i==0: return_list[-1][1] += 1; n //= i if n!=1: return_list.append([n,1]) return return_list def isqrt(n): m = int(n**0.5) if m**2>n: m -= 1 if (m+1)**2<=n: m += 1 return m from math import gcd pn = PrimeNumbers(10**9) for _ in range(int(input())): pu,qu,pv,qv = map(int,input().split()) while not qu-pu==qv-pv==1: if qu-pu==qv-pv: if pu>pv: pu,qu,pv,qv = pv,qv,pu,qu diff = set() for x,_ in pn.prime_factorization(qu-pu): diff.add(x-pu%x) m = min(diff) if pu+m>pv: break d = gcd(pu+m,qu+m); pu = (pu+m)//d; qu = (qu+m)//d else: if qu-pu