You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.

Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?


-----Input-----

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.

Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 10^9; 0 ≤ p ≤ q ≤ 10^9; y > 0; q > 0).

It is guaranteed that p / q is an irreducible fraction.

Hacks. For hacks, an additional constraint of t ≤ 5 must be met.


-----Output-----

For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.


-----Example-----
Input
4
3 10 1 2
7 14 3 8
20 70 2 7
5 6 1 1

Output
4
10
0
-1



-----Note-----

In the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.

In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.

In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.

In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.

Difficulty: MEDIUM_HARD
Tags: Sorting

Mathematics
Skill types: Sorting

Starter code:

Solutions:
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if x * b == y * a:
		print(0)
		continue
	if a == b and x != y:
		print(-1)
		continue

	def check(mid):
		mid *= b
		mid = mid - y
		if (y + mid) % b == 0 and Fraction(x + mid, y + mid) >= Fraction(a, b) and (Fraction(x, y + mid) <= Fraction(a, b)):
			return True
		return False
	st = y // b + 1
	end = 10 ** 15
	ans = end
	while st <= end:
		mid = (st + end) // 2
		if check(mid) == True:
			ans = mid * b - y
			end = mid - 1
		else:
			st = mid + 1
	if ans == 10 ** 15:
		ans = -1
	print(ans)


def gcd(a, b):
	if a == 0:
		return [b, 0, 1]
	d = gcd(b % a, a)
	return [d[0], d[2] - b // a * d[1], d[1]]
t = int(input())
while t > 0:
	t -= 1
	(x, y, p, q) = list(map(int, input().split()))
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	a = p - q
	b = p
	c = q * x - p * y
	(g, xa, ya) = gcd(abs(a), abs(b))
	if c % g != 0:
		print(-1)
	else:
		xa *= c // g
		ya *= c // g
		if a < 0:
			xa = -xa
		if b < 0:
			ya = -ya
		if xa < 0:
			gaps = (-xa + b // g - 1) // (b // g)
			xa += gaps * (b // g)
			ya -= gaps * (a // g)
		if ya < 0:
			gaps = (-ya + -a // g - 1) // (-a // g)
			xa += gaps * (b // g)
			ya -= gaps * (a // g)
		if xa < 0 or ya < 0:
			print(-1)
		else:
			addon = min(xa // (b // g), ya // (-a // g))
			xa -= addon * (b // g)
			ya += addon * (a // g)
			print(xa + ya)


import sys

def solve():
	t = int(sys.stdin.readline())
	for ti in range(t):
		(x, y, p, q) = map(int, sys.stdin.readline().split())
		if p == 0:
			if x == 0:
				print(0)
			else:
				print(-1)
			continue
		if p == q:
			if x == y:
				print(0)
			else:
				print(-1)
			continue
		if p * y == x * q:
			print(0)
		elif p * y > x * q:
			z = (q * (y - x) + q - p - 1) // (q - p)
			ans = (z + q - 1) // q * q - y
			print(ans)
		else:
			z = (q * x + p - 1) // p
			ans = (z + q - 1) // q * q - y
			print(ans)
solve()


def gcd(a, b):
	if a == 0:
		return (b, 0, 1)
	(g, x1, y1) = gcd(b % a, a)
	y = x1
	x = y1 - b // a * x1
	return (g, x, y)

def comp(da, db, t, a, b):
	ra = a + da * t
	rb = b + db * t
	return ra + rb

def solve():
	(x, y, p, q) = map(int, input().split())
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		return
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		return
	r = x * q - y * p
	(g, a, b) = gcd(p - q, p)
	if r % g != 0:
		print(-1)
		return
	a *= r // g
	b *= r // g
	da = p
	db = q - p
	minT = -10 ** 18
	minT = max(minT, (-a + (da - 1)) // da)
	minT = max(minT, (-b + (db - 1)) // db)
	t = minT
	rr = comp(da, db, t, a, b)
	print(rr)

def main():
	t = int(input())
	for i in range(t):
		solve()
main()


def mp():
	return map(int, input().split())

def lt():
	return list(map(int, input().split()))

def pt(x):
	print(x)

def ip():
	return input()

def it():
	return int(input())

def sl(x):
	return [t for t in x]

def spl(x):
	return x.split()

def aj(liste, item):
	liste.append(item)

def bin(x):
	return '{0:b}'.format(x)

def listring(l):
	return ' '.join([str(x) for x in l])

def ptlist(l):
	print(' '.join([str(x) for x in l]))
t = it()
for _ in range(t):
	(x, y, p, q) = mp()
	if p == q:
		if x == y:
			pt(0)
		else:
			pt(-1)
	elif p == 0:
		if x == 0:
			pt(0)
		else:
			pt(-1)
	else:
		r = (y + q - 1) // q
		(xa, ya) = (r * p, r * q)
		if xa < x:
			m = (x - xa + p - 1) // p
		else:
			m = 0
		if xa - x > ya - y:
			n = (xa - x - (ya - y) + q - p - 1) // (q - p)
		else:
			n = 0
		pt(ya + q * max(m, n) - y)


t = int(input())
for _ in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == q:
		print(0 if x == y else -1)
	elif p == 0:
		print(0 if x == 0 else -1)
	elif x * q == y * p:
		print(0)
	else:
		l = 0
		r = 2 ** 64
		cnt = 0
		while l + 1 < r:
			cnt += 1
			c = (l + r) // 2
			if x <= c * p <= x + c * q - y:
				r = c
			else:
				l = c
		print(r * q - y)


from sys import stdin, stdout
from math import ceil

def GCD(a, b):
	if not b:
		return a
	else:
		return GCD(b, a % b)
t = int(stdin.readline())
for i in range(t):
	(x, y, p, q) = map(int, stdin.readline().split())
	l = -1
	r = 10 ** 50
	while r - l > 1:
		m = (r + l) // 2

		def check(m):
			if p * m >= x:
				a = p * m - x
				b = q * m - y - a
				if b < 0:
					a = -1
				else:
					a += b
				return a
			else:
				return -1
		if check(m) >= 0:
			r = m
		else:
			l = m
	ans = check(r)
	stdout.write(str(ans) + '\n')


from sys import stdout, stdin, setrecursionlimit
from bisect import insort, bisect_right, bisect_left
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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:
			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')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))
(graph, mod, szzz) = ({}, 10 ** 9 + 7, lambda : sorted(zzz()))

def getStr():
	return input()

def getInt():
	return int(input())

def listStr():
	return list(input())

def getStrs():
	return input().split()

def isInt(s):
	return '0' <= s[0] <= '9'

def input():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in input().split()]

def output(answer, end='\n'):
	stdout.write(str(answer) + end)

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def primeNums():
	N = 10 ** 5
	SN = int(sqrt(N))
	sieve = [i for i in range(N + 1)]
	sieve[1] = 0
	for i in sieve:
		if i > SN:
			break
		if i == 0:
			continue
		for j in range(2 * i, N + 1, i):
			sieve[j] = 0
	prime = [i for i in range(N + 1) if sieve[i] != 0]
	return prime

def primeFactor(n):
	lst = []
	mx = int(sqrt(n)) + 1
	for i in prime:
		if i > mx:
			break
		while n % i == 0:
			lst.append(i)
			n //= i
	if n > 1:
		lst.append(n)
	return lst
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in range(getInt()):
	(x, y, p, q) = zzz()
	mx = 0
	mn = 10 ** 10
	while mx < mn:
		mid = (mx + mn) // 2
		(np, nq) = (mid * p, mid * q)
		if nq >= y and np >= x:
			if nq - y >= np - x:
				mn = mid
			else:
				mx = mid + 1
		else:
			mx = mid + 1
	print(mn * q - y if mn != 10 ** 10 else -1)


for case in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	lo = 0
	hi = 10 ** 10
	while lo < hi:
		mid = lo + (hi - lo) // 2
		(np, nq) = (mid * p, mid * q)
		if nq >= y and np >= x:
			if nq - y >= np - x:
				hi = mid
			else:
				lo = mid + 1
		else:
			lo = mid + 1
	print(lo * q - y if lo != 10 ** 10 else -1)


def get(a, b):
	if b % a == 0:
		return 0
	else:
		return a - b % a
INF = 10000000000000000000000000

def go(y, x, p, q):
	global INF
	if q * y == p * x:
		return get(q, x)
	elif q * y > x * p:
		l = 0
		r = INF
		ans = r
		while l <= r:
			m = (l + r) // 2
			if p * m >= y:
				ans = min(ans, m)
				r = m - 1
			else:
				l = m + 1
		if ans == INF:
			return -1
		return ans * q - x
	else:
		l = x
		r = INF
		ans = r
		while l <= r:
			m = (l + r) // 2
			k1 = (m - x + y) * q
			k2 = p * m
			if k1 >= k2:
				ans = min(ans, m)
				r = m - 1
			else:
				l = m + 1
		if ans == INF:
			return -1
		return ans - x + get(q, ans)
	return -1
t = int(input())
for _ in range(t):
	l = list(map(int, input().split()))
	print(go(l[0], l[1], l[2], l[3]))


def div(a, b):
	return (a + b - 1) // b
for t in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	if q == 1:
		if p == 0 and x == 0 or (p == 1 and x == y):
			print(0)
		else:
			print(-1)
	else:
		z = max(max(div(x, p), div(y, q)), max(div(y - x, q - p), 0))
		print(z * q - y)


def gcd(a, b):
	if b > a:
		return gcd(b, a)
	if b == 0:
		return a
	return gcd(b, a % b)

def works(a, b, c, d, x):
	return b <= d * x and a <= c * x and (d * x - b >= c * x - a)

def solve():
	(a, b, c, d) = list(map(int, input().rstrip().split()))
	if c == d == 1 and (not a / b == 1):
		print(-1)
		return
	if c == 0 and (not a == 0):
		print(-1)
		return
	g = gcd(c, d)
	c //= g
	d //= g
	low = -1
	high = 1000000000000
	while low + 1 < high:
		mid = (low + high) // 2
		if works(a, b, c, d, mid):
			high = mid
		else:
			low = mid
	print(d * high - b)

def __starting_point():
	t = int(input())
	for _ in range(t):
		solve()
__starting_point()


from math import ceil
for _ in range(int(input())):
	(x, y, p, q) = list(map(int, input().split()))
	if p == q and x != y:
		print(-1)
	elif p == q:
		print(0)
	elif p == 0 and x == 0:
		print(0)
	elif p == 0:
		print(-1)
	else:
		a = y // q
		r = y % q
		g1 = (x - p * a + p - 1) // p
		g2 = ceil((x - r - p * a) / (p - q))
		print(max(g1, g2) * q - r)


def ceil(x, y):
	return x // y + (x % y != 0)
for _ in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	if p == 0:
		print(0 if x == 0 else -1)
	elif p == q:
		print(0 if x == y else -1)
	else:
		k = max(ceil(y * q - q * x, q * (q - p)), ceil(x, p))
		a = k * p - x
		b = k * q - (a + y)
		print(a + b)


def check(np, nq):
	return np >= x and nq >= y and (np - x <= nq - y)
t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	l = 0
	r = 10 ** 18
	while l < r - 1:
		m = (l + r) // 2
		if check(p * m, q * m):
			r = m
		else:
			l = m
	if r == 10 ** 18:
		print(-1)
	else:
		ans = q * r - y
		print(ans)


def Ans(k):
	(x, y, p, q) = (k[0], k[1], k[2], k[3])
	if p / q == 1 and x != y or (p == 0 and x != 0):
		print(-1)
	elif p == 0 and x == 0:
		print(0)
	else:
		up = 10 ** 9
		down = 1
		dy = y - x
		while up > down + 1:
			mid = (up + down) // 2
			qf = q * mid
			pf = p * mid
			dq = qf - pf
			if qf - y >= dq - dy and qf >= y and (dq >= dy):
				up = mid
			else:
				down = mid
		if q * down - y >= (q - p) * down - dy and q * down >= y and ((q - p) * down >= dy):
			print(q * down - y)
		elif q * mid - y >= (q - p) * mid - dy and q * mid >= y and ((q - p) * mid >= dy):
			print(q * mid - y)
		else:
			print(q * up - y)
t = int(input())
k = [0] * t
for i in range(t):
	k[i] = list(map(int, input().split()))
for i in range(t):
	Ans(k[i])


for _ in range(int(input())):
	(x, y, p, q) = list(map(int, input().split()))
	(l, r, res) = (0, 10 ** 18, -1)
	while l <= r:
		mid = (l + r) // 2
		(a, b) = (p * mid - x, q * mid - y)
		if a <= b and a > -1 and (b > -1):
			res = b
			r = mid - 1
		else:
			l = mid + 1
	print(res)


def solve():
	(x, y, p, q) = map(int, input().split())
	if p == 0:
		if x == 0:
			print(0)
			return
		else:
			print(-1)
			return
	if p == q:
		if x == y:
			print(0)
			return
		else:
			print(-1)
			return
	var1 = (p + x - 1) // p
	var2 = (y - x + (q - p) - 1) // (q - p)
	max1 = max(var1, var2)
	solution = max1 * q - y
	print(solution)
	return

def main():
	n = int(input())
	for i in range(n):
		solve()
main()


R = lambda : map(int, input().split())
mx = 10 ** 9 + 7
t = int(input())
for i in range(t):
	(a, b, p, q) = R()
	(l, r) = (1, mx)
	while l < r:
		k = (l + r) // 2
		(x, y) = (k * p - a, k * q - b)
		if 0 <= x <= y and y >= 0:
			r = k
		else:
			l = k + 1
	if r >= mx:
		print('-1')
	else:
		print(r * q - b)


import math
t = int(input())
for cs in range(t):
	(x, y, p, q) = [int(x) for x in input().split()]
	(g, h) = (math.gcd(x, y), math.gcd(p, q))
	if x // g == p // h and y // g == q // h:
		print(0)
	elif p == 0 or p == q or p * (1 << 100) - x > q * (1 << 100) - y:
		print(-1)
	else:
		print(max(math.ceil((x - y) / (p - q)), math.ceil(x / p)) * q - y)


def ext_gcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, x, y) = ext_gcd(b % a, a)
		return (g, y - b // a * x, x)

def multinv(b, n):
	(g, x, trash) = ext_gcd(b, n)
	return x % n

def solve():
	(x, y, p, q) = map(int, input().split(' '))
	if p == q:
		if x == y:
			return 0
		else:
			return -1
	if p == 0:
		if x == 0:
			return 0
		else:
			return -1
	c = p * y - q * x
	a = multinv(q, p) * c % p
	if (q * a - c) // p < a:
		dif = c // (q - p) - a
		dif = dif // p
		a += p * (dif - 3)
		while (q * a - c) // p < a or a < 0:
			a += p
	return (q * a - c) // p
t = int(input())
for a0 in range(t):
	print(solve())


def mi():
	return map(int, input().split())
from math import ceil as c
for _ in range(int(input())):
	(x, y, p, q) = mi()
	bestans = -1
	low = 0
	high = 10 ** 9
	while low <= high:
		mid = (low + high) // 2
		p1 = p * mid
		q1 = q * mid
		successful = p1 - x
		unsuccessful = q1 - y - successful
		if successful < 0 or unsuccessful < 0:
			low = mid + 1
		else:
			high = mid - 1
			bestans = successful + unsuccessful
	print(int(bestans))


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	left = -1
	right = 10 ** 9
	r = right
	while left + 1 < right:
		t = (left + right) // 2
		if p * t >= x and q * t - p * t >= y - x:
			right = t
		else:
			left = t
	if not (p * r >= x and q * r - p * r >= y - x):
		print(-1)
	else:
		print(q * right - y)


qq = int(input())
while qq > 0:
	(x, y, p, q) = map(int, input().split())
	l = 1
	r = 1000000001
	while l < r:
		mid = (l + r) // 2
		curr = mid * q
		curr2 = curr * p // q
		if curr >= y and curr2 >= x and (curr - y >= curr2 - x):
			r = mid
		else:
			l = mid + 1
	if l == 1000000001:
		print('-1')
	else:
		print(int(l * q - y))
	qq = qq - 1


def xgcd(a, b):
	if b == 0:
		return (1, 0)
	(x1, y1) = xgcd(b, a % b)
	return (y1, x1 - a // b * y1)

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
for kek in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	v = p * y - q * x
	g = gcd(q - p, p)
	(k0, l0) = xgcd(q - p, p)
	l0 *= -1
	g1 = v // g
	k0 *= g1
	l0 *= g1
	xx = (-k0 + p - 1) // p
	xx = max(xx, (-l0 + q - p - 1) // (q - p))
	l = l0 + xx * (q - p)
	k = k0 + xx * p
	print(k + l)


import sys

def de(x, y):
	if x % y == 0:
		return x // y
	return x // y + 1

def euc(a, b):
	if b == 0:
		return (1, 0)
	(x, y) = euc(b, a % b)
	return (-y, -x - y * (a // b))

def solve(x, y, p, q):
	if q == p:
		if x == y:
			return 0
		return -1
	if p == 0:
		if x == 0:
			return 0
		return -1
	(a0, b0) = euc(p, q)
	g = a0 * p - q * b0
	c = x * q - p * y
	if c % g:
		return -1
	a0 = a0 * (c // g)
	b0 = b0 * (c // g)
	t1 = a0 // q
	t = max(de(b0 - a0, q - p), de(-b0, p))
	a = a0 + q * t
	b = b0 + p * t
	return a
t = int(input())
for it in range(t):
	(x, y, p, q) = list(map(int, input().split()))
	print(solve(x, y, p, q))


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == 1 and q == 1 and (x // y != 1) or (p == 0 and x != 0):
		z = -1
	else:
		start = 0
		stop = 10 ** 9
		while start <= stop - 2:
			mid = (start + stop) // 2
			if mid * q - y + x >= mid * p and mid * q >= y and (mid * p >= x):
				stop = mid
			else:
				start = mid
		z = stop * q - y
	print(z)


for _ in range(int(input())):
	(x, y, p, q) = list(map(int, input().split()))
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	if x % p == 0:
		k = x // p
	else:
		k = x // p + 1
	if (y - x) % (q - p) == 0:
		k = max(k, (y - x) // (q - p))
	else:
		k = max(k, (y - x) // (q - p) + 1)
	print(k * q - y)


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == q:
		if x != y:
			print(-1)
		elif x == y == 0:
			print(1)
		else:
			print(0)
		continue
	if p == 0:
		if x == 0:
			if y == 0:
				print(1)
			else:
				print(0)
		else:
			print(-1)
		continue
	k = max((y - x + q - p - 1) // (q - p), (x + p - 1) // p)
	print(k * q - y)


import math

def main():
	tt = int(input())
	for qq in range(tt):
		A = [int(i) for i in input().split()]
		(x, y, p, q) = (A[0], A[1], A[2], A[3])
		if x * q == y * p and x != 0 and (p != 0):
			print(0)
			continue
		if x == p and y == q or (p == 0 and x == 0):
			print(0)
			continue
		elif p == q and x != y or (p == 0 and x != 0):
			print(-1)
			continue
		a = math.ceil((y - x) / (q - p))
		b = math.ceil(x / p)
		ans = q * max(a, b) - y
		print(ans)
main()


def gcd(a, b):
	if a == 0:
		return (b, 0, 1)
	(g, x, y) = gcd(b % a, a)
	return (g, y - b // a * x, x)
t = int(input())
for i in range(t):
	(x, y, p, q) = list(map(int, input().split()))
	val = p * y - q * x
	(g, a, b) = gcd(q, -p)
	if val % g != 0:
		print(-1)
		continue
	a *= val // g
	b *= val // g
	da = abs(p // g)
	db = abs(q // g)
	if a < 0:
		if da == 0:
			print(-1)
			continue
		mul = (abs(a) + da - 1) // da
		a += mul * da
		b += mul * db
	if b < 0:
		if db == 0:
			print(-1)
			continue
		mul = (abs(b) + db - 1) // db
		a += mul * da
		b += mul * db
	if a > b:
		if da == db:
			print(-1)
			continue
		diff = a - b
		step = db - da
		mul = (diff + step - 1) // step
		a += mul * da
		b += mul * db
	mul = b // db
	if da != 0:
		mul = min(mul, a // da)
	if da != db:
		mul = min(mul, (b - a) // (db - da))
	print(b - db * mul)


import math
import sys
t = int(input())
for j in range(1, t + 1):
	(x, y, p, q) = map(int, input().split())
	f1 = 0
	if p != q and p != 0:
		tmp = max((y - x + (q - p) - 1) // (q - p), (x + p - 1) // p)
		print(q * tmp - y)
		f1 = 1
	if p == 0 and x == 0:
		print(0)
	elif p == q and x == y:
		print(0)
	elif not f1:
		print(-1)


N = int(input())
import math
for _ in range(N):
	(x, y, p, q) = [int(x) for x in input().split()]
	if p == 0 or p == q:
		if x * q == p * y:
			print(0)
		else:
			print(-1)
		continue
	n = math.ceil((y - x) / (q - p))
	n = max(n, math.ceil(x / p))
	n = max(n, math.ceil(y / q))
	print(n * q - y)


import math
for _ in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	if q == p:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	t = int(math.ceil(max((y - x) / (q - p), x / p)))
	print(q * t - y)


t = int(input())
for i in range(t):
	(x, y, p, q) = [int(i) for i in input().split()]
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	l = 0
	r = 10000000000
	while l < r:
		t = (l + r) // 2
		c1 = p * t - x
		c2 = q * t - y - c1
		if c1 >= 0 and c2 >= 0:
			r = t
		else:
			l = t + 1
	if r == 10000000000:
		print(-1)
	else:
		print(q * l - y)


INF = 10 ** 40

def gcd_ex(A, B):
	if A == 0:
		return (B, 0, 1)
	(g, a1, b1) = gcd_ex(B % A, A)
	a = b1 - B // A * a1
	b = a1
	return (g, a, b)

def round_down(a, b):
	s = (a < 0) != (b < 0)
	a = abs(a)
	b = abs(b)
	if not s:
		return a // b
	return -((a + b - 1) // b)

def round_up(a, b):
	s = (a < 0) != (b < 0)
	a = abs(a)
	b = abs(b)
	if not s:
		return (a + b - 1) // b
	return -(a // b)

def solve():
	(x, y, p, q) = map(int, input().split())
	A = q
	B = -p
	C = p * y - q * x
	(g, a0, b0) = gcd_ex(A, -B)
	b0 *= -1
	if C % g != 0:
		print(-1)
		return
	a0 *= C // g
	b0 *= C // g
	k_up1 = 0
	if B == 0:
		if -a0 > 0:
			print(-1)
			return
		k_up1 = INF
	else:
		k_up1 = round_down(-a0, B // g)
	k_down2 = 0
	k_up2 = 0
	if A + B == 0:
		if b0 - a0 < 0:
			print(-1)
			return
		k_down2 = -INF
		k_up2 = INF
	elif A + B > 0:
		k_down2 = -INF
		k_up2 = round_down(b0 - a0, (A + B) // g)
	else:
		k_down2 = round_up(b0 - a0, (A + B) // g)
		k_up2 = INF
	k_down = k_down2
	k_up = min(k_up1, k_up2)
	if k_down > k_up:
		print(-1)
		return
	if k_up == INF:
		raise Exception
	b = b0 - A // g * k_up
	print(b)

def main():
	t = int(input())
	for i in range(t):
		solve()
main()


def check(k1, k2, rr):
	k3 = p * k2 - rr
	return k3 >= 0 and k2 * q + k1 >= k3

def binary_search(k1, rr):
	r = 1
	while not check(k1, r, rr):
		r *= 2
	l = -1
	while l + 1 < r:
		m = (l + r) // 2
		if check(k1, m, rr):
			r = m
		else:
			l = m
	return r
n = int(input())
for _ in range(n):
	(x, y, p, q) = map(int, input().split())
	if p == 0 and x != 0 or (p == q and x != y):
		print(-1)
		continue
	k1 = (y + q - 1) // q * q - y
	y += k1
	rr = x - y // q * p
	r = binary_search(k1, rr)
	print(r * q + k1)


tc = int(input())
for i in range(tc):
	(x, y, p, q) = map(int, input().split())
	if p == 0:
		if x == 0:
			print('0')
		else:
			print('-1')
	elif p == q:
		if y > x:
			print('-1')
		else:
			print('0')
	elif p * y == x * q:
		print('0')
	else:

		def minmax(lob, hib):
			if lob == hib:
				return lob - y
			lower = (lob + hib) // 2
			higher = lower + q - lower % q
			lower = higher - q
			newxh = higher // q * p
			if 0 <= newxh - x <= higher - y:
				newxl = lower // q * p
				if 0 <= newxl - x <= lower - y:
					return minmax(lob, lower)
				else:
					return higher - y
			else:
				return minmax(higher, hib)
		lob = y + q - y % q
		hib = 10 ** 19 + q - 10 ** 19 % q
		print(str(minmax(lob, hib)))


def check(x, y, p, q, t):
	if p * t >= x and q * t - p * t >= y - x:
		return 1
	return 0
n = int(input())
for i in range(n):
	(x, y, p, q) = map(int, input().split())
	(l, r) = (-1, 10 ** 9)
	if not check(x, y, p, q, r):
		print(-1)
		continue
	while r - l > 1:
		m = (r + l) // 2
		if check(x, y, p, q, m):
			r = m
		else:
			l = m
	print(r * q - y)


from fractions import gcd
t = int(input())

def ok(x, y, p, q, n):
	np = n * p
	nq = n * q
	a_needed = np - x
	b_needed = nq - y - a_needed
	if a_needed < 0 or b_needed < 0:
		return False
	return True
while t > 0:
	t -= 1
	(x, y, p, q) = [int(x) for x in input().split()]
	low = 0
	high = int(1e+36)
	poss = -1
	while high >= low:
		mid = (high + low) // 2
		if ok(x, y, p, q, mid):
			poss = mid
			high = mid - 1
		else:
			low = mid + 1
	if poss == -1:
		print(poss)
	else:
		a_needed = poss * p - x
		b_needed = poss * q - y - a_needed
		print(a_needed + b_needed)


def chec(a, b, p, q, mid):
	if p * r >= a and (q - p) * mid >= b - a:
		return True
	else:
		return False

def check(np, nq):
	return np >= a and nq >= b and (np - a <= nq - b)
for _ in range(int(input())):
	(a, b, p, q) = map(int, input().split())
	l = 0
	r = 10000000000
	if check(p * r, q * r) == False:
		print(-1)
		continue
	while l <= r:
		mid = l + (r - l) // 2
		if check(p * mid, q * mid):
			r = mid - 1
		else:
			l = mid + 1
	print(l * q - b)


for _ in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	d = q * int(1000000000.0)
	c = p * int(1000000000.0)
	if not (d >= y and c >= x and (d - y >= c - x)):
		print(-1)
		continue
	i = -1
	j = int(1000000000.0)
	while i <= j:
		m = (i + j) // 2
		d = q * m
		c = p * m
		if d >= y and c >= x and (d - y >= c - x):
			j = m - 1
		else:
			i = m + 1
	print(i * q - y)


import math as mt
import sys, string, bisect
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
d = defaultdict(int)

def extended_gcd(a, b):
	if a == 0:
		return (0, 1)
	(x, y) = extended_gcd(b % a, a)
	return (y - b // a * x, x)

def check(x, y, p, q):
	if p >= x and y - x + p <= q:
		return True
	return False
t = I()
for _ in range(t):
	(x, y, p, q) = M()
	if p == 0 and x != 0:
		print(-1)
	else:
		g = mt.gcd(x, y)
		if x // g == p and y // g == q:
			print(0)
		elif p == q:
			print(-1)
		else:
			l = 0
			r = 1
			while not check(x, y, p * r, q * r):
				l = r
				r *= 10
			d = 0
			while l <= r:
				m = (l + r) // 2
				if check(x, y, p * m, q * m):
					d = m
					r = m - 1
				else:
					l = m + 1
			if q * d - y < 0:
				print(-1)
			else:
				print(q * d - y)


import math
t = int(input())
for cs in range(t):
	(x, y, p, q) = [int(x) for x in input().split()]
	(g, h) = (math.gcd(x, y), math.gcd(p, q))
	(L, R) = (0, 1 << 100)
	if x // g == p // h and y // g == q // h:
		print(0)
	elif p == 0 or p == q or p * R - x > q * R - y:
		print(-1)
	else:
		while L < R - 1:
			M = L + R >> 1
			if 0 <= p * M - x and p * M - x <= q * M - y:
				R = M
			else:
				L = M
		print(q * R - y)


t = int(input())
for _ in range(t):
	(x, y, a, b) = map(int, input().split())
	if a == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	lo = max(-(-x // a), -(-y // b))
	hi = 10 ** 18
	while lo < hi:
		k = lo + (hi - lo) // 2
		if k * (a - b) <= x - y:
			hi = k
		else:
			lo = k + 1
	if lo * (a - b) <= x - y:
		print(lo * b - y)
	else:
		print(-1)


def solve(x, y, p, q):
	if p == 0:
		return 0 if x == 0 else -1
	pp = (x - 1) // p + 1 if p != 0 else 0
	L = max((y - 1) // q + 1, pp) - 1
	L = max(L, -1)
	z = y - x
	INF = L + 10 ** 10
	R = INF
	while R - L > 1:
		M = L + R >> 1
		cur = q * M
		curp = p * M
		curz = cur - curp
		dl = cur - y
		if curp >= x and curz >= z:
			R = M
		else:
			L = M
	if R == INF:
		return -1
	return R * q - y
read = lambda : map(int, input().split())
t = int(input())
for i in range(t):
	(x, y, p, q) = read()
	print(solve(x, y, p, q))


def gcd(a, b):
	if a == 0:
		return [b, 0, 1]
	(d, x1, y1) = gcd(b % a, a)
	return [d, y1 - b // a * x1, x1]

def find_any_solution(a, b, c):
	(g, x0, y0) = gcd(abs(a), abs(b))
	if c % g != 0:
		return [False, 0, 0, 0]
	x0 *= c // g
	y0 *= c // g
	if a < 0:
		x0 *= -1
	if b < 0:
		y0 *= -1
	return [True, x0, y0, g]

def main():
	(x, y, p, q) = [int(i) for i in input().split()]
	if p == 0 and x != 0:
		print(-1)
		return 0
	ok = find_any_solution(q, -p, p * y - x * q)
	if not ok[0]:
		print(-1)
		return
	a = ok[1]
	b = ok[2]
	g = ok[3]
	ag = q // g
	bg = -p // g
	if ag == -1 * bg and a > b:
		print(-1)
		return 0
	(l, r) = (-10 ** 18, 10 ** 18)
	while r - l > 1:
		m = (l + r) // 2
		if a + m * bg >= 0:
			l = m
		else:
			r = m
	maxk = l
	(l, r) = (-10 ** 18, 10 ** 18)
	while r - l > 1:
		m = (l + r) // 2
		if b - m * ag >= 0:
			l = m
		else:
			r = m
	maxk = min(maxk, l)
	(l, r) = (-10 ** 18, 10 ** 18)
	while r - l > 1:
		m = (l + r) // 2
		if a + m * bg <= b - m * ag:
			l = m
		else:
			r = m
	if ag != bg * -1:
		maxk = min(l, maxk)
	if b - maxk * ag + y == 0:
		--maxk
	if b - maxk * ag + y == 0:
		print(-1)
		return
	print(b - maxk * ag)
t = int(input())
for i in range(t):
	main()


MAXN = int(2e+18)

def check(n, x, y, p, q):
	(np, nq) = (n * p, n * q)
	if nq < y:
		return False
	diff = nq - y
	return x <= np <= x + diff

def solve():
	(x, y, p, q) = map(int, input().split())
	(l, r) = (1, int(MAXN))
	while l != r:
		m = (l + r) // 2
		if not check(m, x, y, p, q):
			l = m + 1
		else:
			r = m
	if r == MAXN:
		print(-1)
	else:
		print(l * q - y)
t = int(input())
for _ in range(t):
	solve()


import sys
inf = 1 << 60

def solve():
	t = int(sys.stdin.readline())
	for i in range(t):
		(x, y, p, q) = map(int, sys.stdin.readline().split())
		if p == 0:
			if x == 0:
				print(0)
			else:
				print(-1)
			continue
		if p == q:
			if x == y:
				print(0)
			else:
				print(-1)
			continue
		if x * q > y * p:
			z0 = (q * x + p - 1) // p
			ans = (z0 + q - 1) // q * q - y
		elif x * q == y * p:
			ans = 0
		else:
			z0 = (q * (y - x) + q - p - 1) // (q - p)
			ans = (z0 + q - 1) // q * q - y
		print(ans)
solve()


import math

def solve():
	(x, y, p, q) = map(int, input().split())
	(l, r) = (0, 10 ** 10)
	inf = 10 ** 10
	while l < r:
		mid = (l + r) // 2
		(mp, mq) = (mid * p, mid * q)
		if mp >= x and mq >= y and (mp - x <= mq - y):
			r = mid
		else:
			l = mid + 1
	print(l * q - y if l != inf else -1)
t = 1
t = int(input())
for _ in range(t):
	solve()


for i in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	print(-(x > 0) if not p else -(y > x) if p == q else max((x - 1) // p, (y - x - 1) // (q - p)) * q + q - y)


def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def get(x, y, p, q):
	(low, high, mid, best) = (1, 1 << 65, 0, -1)
	while low <= high:
		mid = low + high + 1 >> 1
		tp = p * mid
		tq = q * mid
		if tq >= y and x <= tp <= x + tq - y:
			best = mid
			high = mid - 1
		else:
			low = mid + 1
	return best
T = int(input())
for _ in range(T):
	(x, y, p, q) = map(int, input().split())
	if x == 0 and p == q:
		print(-1)
		continue
	if x == y and p == 0:
		print(-1)
		continue
	if x == 0 and p == 0:
		print(0)
		continue
	(nx, ny) = (x, y)
	nx //= gcd(x, y)
	ny //= gcd(x, y)
	need = get(nx, ny, p, q)
	rx = need * p
	ry = need * q
	(low, high, mid, best) = (0, 1 << 63, 0, -1)
	while low <= high:
		mid = low + high + 1 >> 1
		if rx + mid * p >= x and ry + mid * q >= y and (ry + mid * q - y >= rx + mid * p - x):
			best = mid
			high = mid - 1
		else:
			low = mid + 1
	if best == -1:
		print(-1)
		continue
	rx += best * p
	ry += best * q
	if rx * q == ry * p:
		print(ry - y)
	else:
		print(-1)


import math

def result():
	(x, y, p, q) = map(int, input().split())
	if p == 1 and q == 1:
		if x == y:
			print(0)
		else:
			print(-1)
		return
	if p == 0 and q == 1:
		if x == 0:
			print(0)
		else:
			print(-1)
		return
	n = max(math.ceil(y / q), math.ceil(x / p), math.ceil((y - x) / (q - p)))
	print(n * q - y)
t = int(input())
for i in range(t):
	result()


tests = int(input())

def generate(x, y, p, q):
	min_a = -1
	max_a = 10 ** 18
	while max_a - min_a > 1:
		mid_a = (max_a + min_a) // 2
		if (x + mid_a) * q < (y + mid_a) * p:
			min_a = mid_a
		else:
			max_a = mid_a
	return max_a
for test in range(tests):
	(x, y, p, q) = map(int, input().split())
	if p == 0:
		print(0 if x == 0 else -1)
	elif q == 1:
		print(0 if x == y else -1)
	else:
		a = generate(x, y, p, q)
		a += (p - x - a) % p
		b = (q - y - a) % q
		cnt = (x + a) // p - (y + a + b) // q
		print(a + b + q * cnt)


from sys import stdin, stdout
t = int(stdin.readline().rstrip())
for _ in range(t):
	(x, y, p, q) = map(int, stdin.readline().rstrip().split())
	if p == 0 and x == 0:
		print(0)
	elif p == 0:
		print(-1)
	elif x == y and p == q:
		print(0)
	elif p == q:
		print(-1)
	else:
		c = max([x // p, y // q, (y - x) // (q - p)])
		if p * c < x or q * c < y or q * c - y < p * c - x:
			c += 1
		print(q * c - y)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import deque
import threading
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')

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
for _ in range(int(input())):
	(x, y, p, q) = map(int, input().split())
	if p == 0 or p == q:
		print(0 if x * q == p * y else -1)
		continue
	n = math.ceil((y - x) / (q - p))
	n = max(n, math.ceil(x / p))
	n = max(n, math.ceil(y / q))
	print(n * q - y)


n = int(input())
for _ in range(n):
	(x, y, p, q) = map(int, input().split())
	if p == 0 and x != 0:
		print(-1)
	elif p == q and x != y:
		print(-1)
	elif p * y == q * x:
		print(0)
	else:
		print(q * max((x + p - 1) // p, (y - x + q - p - 1) // (q - p)) - y)


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == q and x != y:
		print(-1)
	elif not p:
		if x:
			print(-1)
		else:
			print(0)
	else:
		r = max((y + q - 1) // q, (x + p - 1) // p)
		if r * p > x + r * q - y:
			if p == q:
				print(0)
			else:
				r = (y - x + q - p - 1) // (q - p)
				print(r * q - y)
		else:
			print(r * q - y)


t = int(input())
for zz in range(t):
	(x, y, p, q) = [int(i) for i in input().split()]
	if x * q == y * p:
		print(0)
	elif p == 0 and x != 0 or (p == q and x != y):
		print(-1)
	else:
		sel1 = y - x
		sel2 = q - p
		kalr = x // p + (0, 1)[x % p != 0]
		kalr = max(kalr, sel1 // sel2 + (0, 1)[sel1 % sel2 != 0])
		q *= kalr
		print(q - y)


import math
import sys
input_ = sys.stdin.readline

def solve3(x, y, p, q):
	if p == q:
		if x == y:
			return 0
		return -1
	if p == 0:
		if x == 0:
			return 0
		return -1
	diff = (q - y % q) % q
	m = (y + diff) / q
	n1 = (x - p * m) / p
	n2 = (m * p - x - diff) / (q - p)
	n = math.ceil(max(n1, n2))
	return diff + n * q

def main():
	t = int(input_())
	solutions = []
	for _ in range(t):
		(x, y, p, q) = map(int, input_().split())
		solutions.append(solve3(x, y, p, q))
	return solutions
solutions = main()
for s in solutions:
	print(s)


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	(l, r) = (1, int(2e+18))
	while l != r:
		m = (l + r) // 2
		if m * q < y:
			l = m + 1
			continue
		if x <= m * p <= x + m * q - y:
			r = m
		else:
			l = m + 1
	if r == int(2e+18):
		print(-1)
	else:
		print(l * q - y)


import math
t = int(input())
for _ in range(t):
	(x, y, p, q) = map(int, input().split())
	if p == 1 and q == 1:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0 and q == 1:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	lo = 0
	hi = 2 ** 65
	while hi - lo > 1:
		mid = (lo + hi) // 2
		k = mid
		if x + k * q - y >= k * p and x <= k * p and (k * q >= y):
			hi = mid
		else:
			lo = mid
	print(q * hi - y)


T = int(input())
for t in range(T):
	(x, y, p, q) = map(int, input().split())
	if p == q and x != y:
		print(-1)
		continue
	INF = 10000000000
	lb = -1
	ub = INF
	mod_y = (q - y % q) % q
	while ub - lb > 1:
		mid = (ub + lb) // 2
		diff = mod_y + q * mid
		bunbo = y + diff
		bunshi = p * bunbo // q
		if bunshi >= x and bunshi - x <= diff:
			ub = mid
		else:
			lb = mid
	if ub == INF:
		print(-1)
	else:
		print(mod_y + q * ub)


def gcd(a, b):
	while a != 0 and b != 0:
		if a > b:
			a = a % b
		else:
			b = b % a
	return a + b

def check(x, y, p, q, m):
	num = p * m
	den = q * m
	return num - x >= 0 and den - y - (num - x) >= 0

def count(x, y, p, q, m):
	num = p * m
	den = q * m
	return num - x + (den - y - (num - x))

def search(x, y, p, q):
	(l, r) = (-1, 10 ** 9 + 1)
	while r - l > 1:
		m = (l + r) // 2
		if check(x, y, p, q, m):
			r = m
		else:
			l = m
	if r == 10 ** 9 + 1:
		print(-1)
	else:
		print(count(x, y, p, q, r))
n = int(input())
for i in range(n):
	(x, y, p, q) = map(int, input().split())
	search(x, y, p, q)


t = int(input())
for xt in range(t):
	(a, b, p, q) = tuple(map(int, input().split()))
	start = 1
	end = 1000000000
	ans = -1
	while start <= end:
		mid = (start + end) // 2
		y = q * mid - b
		x = mid * p - a
		if x <= y and x >= 0 and (y >= 0):
			ans = y
			end = mid - 1
		else:
			start = mid + 1
	print(ans)


import math
import sys
import bisect
from heapq import heapify, heappop, heappush
from itertools import *
from collections import deque, OrderedDict
sys.setrecursionlimit(10 ** 6)
II = lambda : sys.stdin.readline()
inp = lambda : int(II())
inpm = lambda : map(int, II().split())
inpl = lambda : list(inpm())
arr_mn = lambda _n, _m: [[0 for __ in range(_m)] for _ in range(_n)]
arr_nn = lambda _n: arr_mn(_n, _n)
EPS = 1e-09
INF = int(1e+18)
MOD = int(1000000000.0) + 7
N = 2000009
mod = 475

def check(p, s):
	i = s // 50 % mod
	for _ in range(25):
		i = (i * 96 + 42) % mod
		if i + 26 == p:
			return True
	return False

def solve():
	(x, y, p, q) = inpm()
	if p == q and x != y:
		print(-1)
		return
	if p == 0:
		if x == 0:
			if y > 0:
				print(0)
			else:
				print(1)
		else:
			print(-1)
		return
	l = max(1, max((x + p - 1) // p, (y + q - 1) // q))
	r = 10 ** 9 + 1
	while r - l > 1:
		m = l + (r - l) // 2
		good = p * m - x
		all = q * m - y
		if all >= good:
			r = m
		else:
			l = m
	good = p * l - x
	all = q * l - y
	if all >= good:
		print(all)
	else:
		print(q * r - y)

def main():
	t = inp()
	for i in range(t):
		solve()
main()


import math

def main():
	T = int(input())
	for t in range(T):
		solve()

def solve():
	(x, y, p, q) = map(int, input().split())
	if p == 1 and q == 1:
		if x == y:
			print(0)
		else:
			print(-1)
		return
	if p == 0 and q == 1:
		if x == 0:
			print(0)
		else:
			print(-1)
		return
	n = max(math.ceil(y / q), math.ceil(x / p), math.ceil((y - x) / (q - p)))
	print(n * q - y)
main()


def solve(x, y, p, q):
	if p == q:
		if x == y:
			return 0
		else:
			return -1
	if p == 0:
		if x == 0:
			return 0
		else:
			return -1
	k1 = (y - x) // (q - p)
	if k1 * (q - p) < y - x:
		k1 += 1
	k2 = y // q
	if k2 * q < y:
		k2 += 1
	k3 = x // p
	if k3 * p < x:
		k3 += 1
	k = max(k1, k2, k3)
	return k * q - y

def main():
	t = int(input())
	for i in range(t):
		(x, y, p, q) = map(int, input().split())
		print(solve(x, y, p, q))
main()


t = int(input())
for tc in range(t):
	(x, y, p, q) = map(int, input().split())
	largenum = 10 ** 18
	c12 = q * largenum - y >= p * largenum - x
	c22 = p * largenum >= x
	c32 = q * largenum >= y
	if not (c12 and c22 and c32):
		print(-1)
		continue
	(left, right) = (0, 10 ** 18)
	while left + 1 < right:
		mid = (left + right) // 2
		c1 = q * mid - y >= p * mid - x
		c2 = p * mid >= x
		c3 = q * mid >= y
		if c1 and c2 and c3:
			right = mid
		else:
			left = mid
	ans = right
	print(int(ans * q - y))


def gcd(a, b):
	if a == 0:
		x = 0
		y = 1
		return (b, x, y)
	(d, x1, y1) = gcd(b % a, a)
	x = y1 - b // a * x1
	y = x1
	return (d, x, y)
t = int(input())
for _ in range(t):
	inp = input().split()
	(x, y, p, q) = (int(inp[0]), int(inp[1]), int(inp[2]), int(inp[3]))
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	c = y * p - x * q
	p = -p
	(g, d1, d2) = gcd(q, p)
	if g < 0:
		c *= -1
		g *= -1
	d1 *= c
	d2 *= c
	if d1 < 0:
		val = abs(d1)
		t = abs(val // abs(p))
		if abs(t * p) < val:
			t += 1
		d1 -= t * p
		d2 += t * q
	elif d1 > 0:
		val = abs(d1)
		t = abs(val // abs(p))
		d1 += t * p
		d2 -= t * q
	if d1 > d2:
		t = (d1 - d2) // (p + q)
		d1 -= t * p
		d2 += t * q
	if d1 > d2:
		d1 -= p
		d2 += q
	print(d2)


def search_k(x, y, p, q):
	lo = 0
	hi = int(1e+18 + 10)
	while lo < hi:
		k = (lo + hi) // 2
		test1 = p * k >= q * x - p * y
		test2 = (q - p) * k >= p * y - q * x
		if test1 and test2:
			hi = k
		else:
			lo = k + 1
	k = lo
	if (k + y) % q > 0:
		k += q - (k + y) % q
	return k
t = int(input())
while t > 0:
	t -= 1
	(x, y, p, q) = input().split(' ')
	x = int(x)
	y = int(y)
	p = int(p)
	q = int(q)
	if p == 1 and q == 1:
		if x < y:
			print('-1')
		else:
			print('0')
		continue
	if p == 0:
		if x > 0:
			print('-1')
		else:
			print('0')
		continue
	print(search_k(x, y, p, q))


import sys
from fractions import gcd as gcdlib

def main():
	t = int(sys.stdin.readline().rstrip())
	for _ in range(t):
		(x, y, p, q) = list(map(int, sys.stdin.readline().split()))
		(res, m, k) = find_best_solution(p - q, p, -(y * p - x * q))
		if res == False:
			result = -1
		elif m < 0 or k < 0:
			result = -1
		else:
			result = m + k
		sys.stdout.write(str(result) + '\n')

def gcdex(a, b):
	if b == 0:
		return (a, 1, 0)
	else:
		(d, x, y) = gcdex(b, a % b)
		return (d, y, x - y * (a // b))

def gcd(a, b):
	if a == 0:
		return (b, 0, 1)
	(d, x, y) = gcd(b % a, a)
	return (d, y - b // a * x, x)

def find_any_solution(a, b, c):
	(g, x0, y0) = gcd(abs(a), abs(b))
	if c % g != 0:
		return (False, None, None)
	x0 *= c // g
	y0 *= c // g
	if a < 0:
		x0 *= -1
	if b < 0:
		y0 *= -1
	return (True, x0, y0)

def find_best_solution(a, b, c):
	(res, x0, y0) = find_any_solution(a, b, c)
	if res == False:
		return (res, x0, y0)
	g = abs(gcdlib(a, b))
	if a == 0:
		k = -x0 // (b // g)
	elif b == 0:
		k = -y0 // (abs(a) // g)
	else:
		k = -min(x0 // (b // g), y0 // (abs(a) // g))
	x = x0 + k * (b // g)
	y = y0 - k * (a // g)
	return (True, x, y)
main()


T = int(input())
for case in range(T):
	(x, y, p, q) = map(int, input().strip().split())
	l = int(0)
	r = int(10000000000.0)
	ans = 1 << 30
	while l <= r:
		mid = int((l + r) / 2)
		A = mid * p - x
		B = mid * q - y
		if A >= 0 and B >= 0 and (A <= B):
			ans = min(ans, mid)
			r = mid - 1
		else:
			l = mid + 1
	if ans < 1 << 30:
		print(ans * q - y)
	else:
		print(-1)


def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

class solution:

	def __init__(self, a=0, b=0):
		self.x = a
		self.y = b

def eu(a, b, sol):
	if a == 0:
		sol.x = 0
		sol.y = 1
		return b
	sol2 = solution()
	d = eu(b % a, a, sol2)
	sol.x = sol2.y - b // a * sol2.x
	sol.y = sol2.x
	return d

def find_any_solution(a, b, c, sol):
	g = eu(abs(a), abs(b), sol)
	if c % g != 0:
		return -1
	sol.x *= c // g
	sol.y *= c // g
	if a < 0:
		sol.x *= -1
	if b < 0:
		sol.y *= -1
	return g

def shift_solution(sol, a, b, cnt):
	sol.x += cnt * b
	sol.y -= cnt * a

def find_all_solution(a, b, c, minx, maxx, miny, maxy):
	sol = solution()
	g = find_any_solution(a, b, c, sol)
	if g == -1:
		return (-1, -1)
	a //= g
	b //= g
	sign_a = 1
	if a < 0:
		sign_a = -1
	sign_b = 1
	if b < 0:
		sign_b = -1
	shift_solution(sol, a, b, (minx - sol.x) // b)
	if sol.x < minx:
		shift_solution(sol, a, b, sign_b)
	if sol.x > maxx:
		return (-1, -1)
	lx1 = sol.x
	shift_solution(sol, a, b, (maxx - sol.x) // b)
	if sol.x > maxx:
		shift_solution(sol, a, b, -sign_b)
	rx1 = sol.x
	shift_solution(sol, a, b, -(miny - sol.y) // a)
	if sol.y < miny:
		shift_solution(sol, a, b, -sign_a)
	if sol.y > maxy:
		return (-1, -1)
	lx2 = sol.x
	shift_solution(sol, a, b, -(maxy - sol.y) // a)
	if sol.y > maxy:
		shift_solution(sol, a, b, sign_a)
	rx2 = sol.x
	if lx2 > rx2:
		(lx2, rx2) = (rx2, lx2)
	lx = max(lx1, lx2)
	rx = min(rx1, rx2)
	if lx > rx:
		return (-1, -1)
	return (lx, rx)

def solve():
	s = input().split()
	x = int(s[0])
	y = int(s[1])
	p = int(s[2])
	q = int(s[3])
	if p == 0:
		if x == 0:
			return 0
		else:
			return -1
	if q == p:
		if x == y:
			return 0
		return -1
	if p * y - q * x == 0:
		return 0
	a = q - p
	b = -p
	c = p * y - q * x
	(ans1, ans2) = find_all_solution(a, b, c, 0, int(10 ** 20), 0, int(10 ** 20))
	ansy1 = (p * y - q * x - (q - p) * ans1) // -p
	ansy2 = (p * y - q * x - (q - p) * ans2) // -p
	sum1 = int(10 ** 25)
	if ans1 >= 0 and ansy1 >= 0 and ((x + ans1) * q == (y + ansy1 + ans1) * p):
		sum1 = min(sum1, ans1 + ansy1)
	if ans2 >= 0 and ansy2 >= 0 and ((x + ans2) * q == (y + ansy2 + ans2) * p):
		sum1 = min(sum1, ans2 + ansy2)
	if sum1 == int(10 ** 25):
		return -1
	return sum1
t = int(input())
for i in range(t):
	print(solve())


def eulid(p, q):
	A = [1, 0]
	B = [0, 1]
	while p != 1 and q != 1:
		if q < 0:
			q = -q
			B[0] = -B[0]
			B[1] = -B[1]
		if p < 0:
			p = -p
			A[0] = -A[0]
			A[1] = -A[1]
		if q < p:
			(p, q) = (q, p)
			(A, B) = (B, A)
		T = q // p
		q = q - T * p
		B[0] = B[0] - T * A[0]
		B[1] = B[1] - T * A[1]
		if q < 0:
			q = -q
			B[0] = -B[0]
			B[1] = -B[1]
		if p < 0:
			p = -p
			A[0] = -A[0]
			A[1] = -A[1]
	if p == 1:
		return A
	elif q == 1:
		return B

def find(x, y, p, q):
	if p == q:
		if x == y:
			return 0
		else:
			return -1
	elif p == 0:
		if x == 0:
			return 0
		else:
			return -1
	elif p * y == x * q:
		return 0
	else:
		A = x * q - p * y
		(a, b) = eulid(p, q)
		(k0, t0) = (A * a, -b * A)
		temp = t0 % p
		r = (temp - t0) // p
		k1 = k0 + r * q
		t1 = t0 + r * p
		if k1 >= t1:
			return k1
		else:
			if (t1 - k1) % (q - p) == 0:
				r = (t1 - k1) // (q - p)
			else:
				r = (t1 - k1) // (q - p) + 1
			k2 = k1 + r * q
			t2 = t1 + r * p
			return k2
T = int(input())
for _ in range(T):
	(x, y, p, q) = list(map(int, input().strip().split(' ')))
	print(find(x, y, p, q))