Polycarp has $x$ of red and $y$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $a$ red candies and $b$ blue candies, or $a$ blue candies and $b$ red candies. Any candy can belong to at most one gift set.

Help Polycarp to find the largest number of gift sets he can create.

For example, if $x = 10$, $y = 12$, $a = 5$, and $b = 2$, then Polycarp can make three gift sets:

In the first set there will be $5$ red candies and $2$ blue candies;

In the second set there will be $5$ blue candies and $2$ red candies;

In the third set will be $5$ blue candies and $2$ red candies.

Note that in this example there is one red candy that Polycarp does not use in any gift set.


-----Input-----

The first line contains an integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.

Each test case consists of a single string containing four integers $x$, $y$, $a$, and $b$ ($1 \le x, y, a, b \le 10^9$).


-----Output-----

For each test case, output one number — the maximum number of gift sets that Polycarp can make.


-----Examples-----

Input
9
10 12 2 5
1 1 2 2
52 311 13 27
1000000000 1000000000 1 1
1000000000 1 1 1000000000
1 1000000000 1000000000 1
1 2 1 1
7 8 1 2
4 1 2 3
Output
3
0
4
1000000000
1
1
1
5
0


-----Note-----

None

Source: codeforces | Difficulty: HARD
Tags: Sorting

Mathematics

Greedy algorithms


Solutions:
t = int(input())
for _ in range(t):
	(x, y, a, b) = map(int, input().split())
	tmp = min((x + y) // (a + b), min(x, y) // min(a, b))
	m1 = min(x, y)
	m2 = min(a, b)
	M1 = max(x, y)
	M2 = max(a, b)
	if a == b:
		print(tmp)
	else:
		d = (m1 - m2 * tmp) // (M2 - m2)
		if M2 * tmp - M1 - (M2 - m2) * d > 0:
			tmp -= 1
		print(tmp)


import math
for t in range(int(input())):
	(x, y, a, b) = tuple(map(int, input().split()))
	m1 = max(a, b)
	m2 = min(a, b)
	if m1 == m2:
		s = math.floor(min(x, y) / m1)
	else:
		s = 0
		if x > y:
			d = math.floor(min((x - y) / (m1 - m2), y / m2, x / m1))
			s += d
			x -= d * m1
			y -= d * m2
		elif y > x:
			d = math.floor(min((y - x) / (m1 - m2), y / m1, x / m2))
			s += d
			y -= d * m1
			x -= d * m2
		d = math.floor(min(x / (m1 + m2), y / (m1 + m2)))
		s += 2 * d
		y -= d * (m1 + m2)
		x -= d * (m1 + m2)
		if x >= a and y >= b or (x >= b and y >= a):
			s += 1
	print(s)


import sys
input = sys.stdin.readline

def foo(x, y, k, a, b):
	if k < 0:
		return -1
	if k * b > x or k * a > y:
		return -1
	if (x - k * b) // a >= (y - k * a) // b:
		return 1
	else:
		return -1

def bsearch(l, r, x, y, a, b):
	while l < r:
		m = (l + r) // 2
		if foo(x, y, m, a, b) == 1:
			l = m + 1
		else:
			r = m
	return l - 1

def f(x, y, a, b, k):
	if k < 0 or x < k * b or y < k * a:
		return -1
	return k + min((x - k * b) // a, (y - k * a) // b)
t = int(input())
for you in range(t):
	l = input().split()
	x = int(l[0])
	y = int(l[1])
	a = int(l[2])
	b = int(l[3])
	if a > b:
		(a, b) = (b, a)
	pp = bsearch(0, 10 ** 10, x, y, a, b)
	ans = max(f(x, y, a, b, pp), f(x, y, a, b, pp + 1))
	pp = bsearch(0, 10 ** 10, y, x, a, b)
	ans = max(f(y, x, a, b, pp), f(y, x, a, b, pp + 1), ans)
	print(ans)


t = int(input())
for i in range(t):
	(x, y, a, b) = list(map(int, input().split()))
	if x > y:
		(x, y) = (y, x)
	if a < b:
		(a, b) = (b, a)
	ans = 0
	if a == b:
		ans = max(ans, x // a)
		print(ans)
	elif a * x - y * b <= 0:
		ans = max(ans, x // b)
		print(ans)
	elif a * y - x * b > 0:
		j = (a * x - y * b) // (a * a - b * b)
		start = max(0, j - 3)
		end = min(start + 6, x // a + 1)
		for j in range(start, end):
			b_poss_x = max(0, (x - j * a) // b)
			a_poss_y = max(0, (y - j * b) // a)
			ans = max(ans, j + min(b_poss_x, a_poss_y))
		print(ans)
	else:
		ans = max(ans, y // b)
		print(ans)


for Z in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(y, x) // a)
		continue
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	ans = 0
	awal_diambil = min((y - x) // (b - a), x // a)
	y -= awal_diambil * b
	x -= awal_diambil * a
	ans += awal_diambil
	akhir_diambil = x // (a + b)
	x -= akhir_diambil * (a + b)
	y -= akhir_diambil * (a + b)
	ans += akhir_diambil * 2
	if x >= a and y >= b:
		ans += 1
	print(ans)


import math
import collections
from itertools import permutations
from itertools import combinations

def prob():
	(x, y, a, b) = [int(x) for x in input().split()]
	start = 0
	end = 10 ** 9 + 10
	if a == b:
		print(min(x, y) // b)
		return
	if a < b:
		(a, b) = (b, a)
	while end - start > 1:
		mid = (end + start) // 2
		left = math.ceil((y - mid * a) / (b - a))
		right = math.floor((x - mid * b) / (a - b))
		if max(left, 0) <= min(right, mid):
			start = mid
		else:
			end = mid
	print(start)
t = 1
t = int(input())
for _ in range(0, t):
	prob()


for i in range(int(input())):
	(r, s, v, u) = list(map(int, input().split()))
	x = min(r, s)
	y = max(r, s)
	a = max(v, u)
	b = min(v, u)
	res = 0
	if a == b:
		res = max(res, x // a)
		print(res)
	elif a * x - y * b <= 0:
		res = max(res, x // b)
		print(res)
	elif a * y - x * b > 0:
		j = (a * x - y * b) // (a ** 2 - b ** 2)
		t1 = max(0, j - 3)
		t2 = min(t1 + 6, x // a + 1)
		for j in range(t1, t2):
			res = max(res, j + min(max(0, (x - j * a) // b), max(0, (y - j * b) // a)))
		print(res)
	else:
		res = max(res, y // b)
		print(res)


import sys
import os
import math
from io import BytesIO, IOBase
from collections import defaultdict, Counter, deque
import bisect
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')

def find(n):
	l = (n * a - y + a - b - 1) // (a - b)
	r = (x - n * b) // (a - b)
	if r - l >= 0 and r >= 0 and (l <= n):
		return 1
	return 0
t = int(input())
for i in range(t):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	if a < b:
		(a, b) = (b, a)
	low = 0
	high = min(x, y)
	while low <= high:
		mid = (low + high) // 2
		if find(mid):
			low = mid + 1
		else:
			high = mid - 1
	print(high)


def check(x, y, a, b, k):
	n = (x - a * k) // (b - a)
	if b > a and n >= 0:
		m = max(0, k - n)
		n = k - m
		if m >= 0 and n * a + m * b <= y:
			return True
	else:
		n = (y - b * k) // (a - b)
		if n >= 0:
			m = max(0, k - n)
			n = k - m
			if m >= 0 and m * a + n * b <= x:
				return True
	return False

def check1(x, y, a, b, k):
	m = (x - b * k) // (a - b)
	if a > b and m >= 0:
		n = max(0, k - m)
		m = k - n
		if n >= 0 and n * a + m * b <= y:
			return True
	else:
		m = (y - a * k) // (b - a)
		if m >= 0:
			n = max(0, k - m)
			m = k - n
			if n >= 0 and m * a + n * b <= x:
				return True
	return False
t = int(input())
t1 = 1
while t > 0:
	vals = list(map(int, input().split()))
	x = vals[0]
	y = vals[1]
	a = vals[2]
	b = vals[3]
	p_sol = (x + y) // (a + b)
	if a == b:
		print(min(x, y) // a)
		t -= 1
		continue
	l = 0
	ans = 0
	while l <= p_sol:
		k = (l + p_sol) // 2
		if check(x, y, a, b, k) or check1(x, y, a, b, k):
			ans = k
			l = k + 1
		else:
			p_sol = k - 1
	print(ans)
	t1 += 1
	t -= 1


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	if y - x <= b - a:
		base1 = x // (a + b)
		base2 = min((x - base1 * (a + b)) // a, (y - base1 * (a + b)) // b)
		print(base1 * 2 + base2)
	else:
		if b == a:
			print(min(x // a, y // b))
			continue
		base1 = (y - x) // (b - a)
		if x // a < base1:
			print(x // a)
			continue
		x -= base1 * a
		y -= base1 * b
		base2 = x // (a + b)
		x -= base2 * (a + b)
		y -= base2 * (a + b)
		ans = base1 + base2 * 2
		if x >= a and y >= b:
			ans += 1
		print(ans)


import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192

def dbg(*args, **kwargs):
	_print('\x1b[95m', end='')
	_print(*args, **kwargs)
	_print('\x1b[0m', end='')

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')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
from itertools import product

def cramer2(a, b, c, d, e, f):
	denominator = a * d - b * c
	if denominator == 0:
		return (None, None)
	return ((e * d - b * f) // denominator, (a * f - e * c) // denominator)

def offset_generator(nums, offset=1, form=0):
	start = 0 if form == 1 else -offset
	end = 1 if form == -1 else offset + 1
	for tp in product(range(start, end), repeat=len(nums)):
		yield [num + off for (num, off) in zip(nums, tp)]

def solve():
	(x, y, a, b) = mpint()
	max_c = min(x // a, y // b)
	max_d = min(x // b, y // a)
	r1 = x - a * max_c
	b1 = y - b * max_c
	r2 = x - a * max_d
	b2 = y - b * max_d
	cramer = cramer2(a, b, b, a, x, y)
	cramer_ans = 0
	if cramer[0] is not None:
		for (c0, d0) in offset_generator(cramer):
			if min(c0, d0) >= 0 and a * c0 + b * d0 <= x and (b * c0 + a * d0 <= y):
				cramer_ans = max(cramer_ans, c0 + d0)
	return max(max_c + (r1 >= b and b1 >= a), max_d + (r2 >= a and b2 >= b), cramer_ans)

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1538/problem/G'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		dbg = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG == 3:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


import sys
input = sys.stdin.readline

def judge(c):
	if not (x >= c * m and y >= c * m):
		return False
	return (x - c * m) // (M - m) + (y - c * m) // (M - m) >= c

def binary_search():
	(l, r) = (0, 10 ** 9 + 10)
	while l <= r:
		m = (l + r) // 2
		if judge(m):
			l = m + 1
		else:
			r = m - 1
	return r
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	m = min(a, b)
	M = max(a, b)
	print(binary_search())


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LI1():
	return list(map(int1, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def LLI1(rows_number):
	return [LI1() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = 10 ** 16
md = 998244353

def ok():
	mn = (-y + a * m + a - b - 1) // (a - b)
	mx = (x - b * m) // (a - b)
	return mn <= mx and max(0, mn) <= min(m, mx)
for testcase in range(II()):
	(x, y, a, b) = LI()
	if a < b:
		(a, b) = (b, a)
	if a == b:
		print(min(x, y) // a)
		continue
	l = -1
	r = (x + y) // (a + b) + 1
	while l + 1 < r:
		m = (l + r) // 2
		if ok():
			l = m
		else:
			r = m
	print(l)


S = sorted
for s in [*open(0)][1:]:
	(x, y, a, b) = map(int, s.split())
	(x, y) = S((x, y))
	(a, b) = S((a, b))
	try:
		c = b - a
		s = a + b
		z = y - x
		A = k = min(z // c, x // a)
		k = min((x := (x - a * k)), (y := (y - b * k))) // s
		A += 2 * k
		(y, x) = S((x - k * s, y - k * s))
		print(A + (x >= b and y >= a))
	except:
		print(x // a)


T = int(input())
for _ in range(T):
	(x, y, a, b) = list(map(int, input().strip().split()))
	if a == b:
		print(min(x, y) // a)
		continue
	if a < b:
		(a, b) = (b, a)
	(left, right) = (0, (x + y) // (a + b))
	while left < right:
		n = (left + right + 1) // 2
		l = max(0, (n * a - y + a - b - 1) // (a - b))
		r = min(n, (x - n * b) // (a - b))
		if l <= r:
			left = n
		else:
			right = n - 1
	print(left)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
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 SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(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 SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(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)
MOD = 10 ** 9 + 7

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
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
ts = int(input())
for case in range(0, ts):
	(x, y, a, b) = [int(p) for p in input().split()]
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(min(x // a, y // b))
		continue
	res = 0
	lo = 1
	hi = 1000000000
	while lo <= hi:
		mid = (lo + hi) // 2
		r1 = x - a * mid
		r2 = y - a * mid
		dif = b - a
		if r1 >= 0 and r2 >= 0 and (r1 // dif + r2 // dif >= mid):
			res = mid
			lo = mid + 1
		else:
			hi = mid - 1
	print(res)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

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

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(x, y, a, b) = mp()
	(x, y) = sorted([x, y])
	(a, b) = sorted([a, b])
	c = 0
	if a == b:
		print(x // a)
		continue
	k = min(x // a, y // b, (y - x) // (b - a))
	if k * a <= x and k * b <= y:
		x -= k * a
		y -= k * b
		c += k
	k = min(x, y) // (a + b)
	x -= k * (a + b)
	y -= k * (a + b)
	print(c + 2 * k + (min(x, y) >= a and max(x, y) >= b))


def gift_set(x, y, a, b):
	if a == b:
		return min(x // a, y // a)
	if a > b:
		(a, b) = (b, a)
	diff = b - a

	def can_make_gifts(mid):
		(minx, miny) = (x - a * mid, y - a * mid)
		can_make_sets = minx // diff + miny // diff >= mid
		return minx >= 0 and miny >= 0 and can_make_sets
	(left, right, res) = (0, 10 ** 9, 0)
	while left <= right:
		mid = (left + right) // 2
		if can_make_gifts(mid):
			res = mid
			left = mid + 1
		else:
			right = mid - 1
	return res
R = lambda : map(int, input().split())
(test_cases,) = R()
for test_case in range(test_cases):
	(x, y, a, b) = R()
	print(gift_set(x, y, a, b))


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	(x, y) = (min(x, y), max(x, y))
	(a, b) = (min(a, b), max(a, b))
	if a == b:
		print(x // a)
	else:
		c = b - a
		z = y - x
		ans = 0
		k = min(z // c, x // a)
		ans += k
		x -= a * k
		y -= b * k
		k = min(x, y) // (a + b)
		ans += 2 * k
		x -= (a + b) * k
		y -= (b + a) * k
		if max(x, y) >= b and min(x, y) >= a:
			ans += 1
		print(ans)


t = int(input())

def readint():
	return int(input())

def intline():
	return [int(e) for e in input().split()]

def factorial(n):
	fact = 1
	res = 0
	for i in range(1, n + 1):
		fact *= i
		if i % 2 == 0:
			res += fact
	return res
global a, b, c, d

def check_point(x, y):
	global a, b, c, d
	(ox, oy) = (int(x), int(y))
	res = 0
	for x in range(ox - 5, ox + 5):
		for y in range(oy - 5, oy + 5):
			if x >= 0 and y >= 0 and (x * a + y * b <= c) and (x * b + y * a <= d):
				score = x + y
				res = max(res, score)
	return res

class Solver:

	def solve(tc):
		global a, b, c, d
		from math import floor
		(c, d, a, b) = intline()
		if c > d:
			(c, d) = (d, c)
		if a > b:
			(a, b) = (b, a)
		ans = 0
		ans = max(ans, check_point(0, 0))
		ans = max(ans, check_point(c / a, 0))
		ans = max(ans, check_point(0, c / b))
		ans = max(ans, check_point(d / a, 0))
		ans = max(ans, check_point(0, d / b))
		if a != b:
			i_y = (c - d * a / b) / (b - a * a / b)
			i_x = (c - i_y * b) / a
			ans = max(ans, check_point(i_x, i_y))
		print(ans)
for tc in range(1, t + 1):
	Solver.solve(tc)


for i in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	if a > b:
		(a, b) = (b, a)
	l = 0
	r = 10 ** 10
	while l < r:
		m = (l + r) // 2
		x1 = x - a * m
		y1 = y - a * m
		if x1 >= 0 and y1 >= 0 and (x1 // (b - a) + y1 // (b - a) >= m):
			l = m + 1
		else:
			r = m
	print(l - 1)


from math import ceil
global x, y, a, b

def f(x, y, a, b):
	if a > b:
		(a, b) = (b, a)
	if a == b:
		return min(x // a, y // b)
	(hi, lo) = (10 ** 9, 0)
	while lo <= hi:
		m = (lo + hi) // 2
		r1 = x - a * m
		r2 = y - a * m
		dif = b - a
		if r1 >= 0 and r2 >= 0 and (r1 // dif + r2 // dif >= m):
			lo = m + 1
		else:
			hi = m - 1
	return lo - 1
for i in range(int(input())):
	(a, b, c, d) = map(int, input().strip().split())
	print(f(a, b, c, d))


t = int(input())
for zvhsuidhuzisdfhucodfgsdfhdfidi in range(t):
	(x, y, a, b) = map(int, input().split())
	cnt = 0
	if a > b:
		t = a
		a = b
		b = t
	if x > y:
		t = x
		x = y
		y = t
	if x // a < y // b:
		answer = x // a
	else:
		answer = y // b
	abc = y * b
	bcd = x * a
	cde = b * b
	efg = a * a
	if a == b:
		a = a
	else:
		cnt = (abc - bcd) // (cde - efg)
	for i in range(cnt, cnt + 2):
		if x - i * a > -1 and y - i * b > -1:
			answer = max(answer, i + min((x - i * a) // b, (y - i * b) // a))
	print(answer)


import time

def main():
	t = i_input()
	for tt in range(t):
		(x, y, a, b) = li_input()
		if a == b:
			print(min(x, y) // a)
			continue
		(a, b) = (max(a, b), min(a, b))
		l = 0
		r = 1 + (x + y) // (a + b)
		while r - l > 1:
			mid = (r + l) // 2
			mink = max(0, a * mid - y)
			maxk = x - b * mid
			if not mink % (a - b):
				mink //= a - b
			else:
				mink = 1 + mink // (a - b)
			if mink <= mid and mink * (a - b) <= maxk:
				l = mid
			else:
				r = mid
		print(l)

def i_input():
	return int(input())

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

def li_input():
	return list(map(int, l_input()))

def il_input():
	return list(map(int, l_input()))
TT = time.time()
main()


import sys
input = lambda : sys.stdin.readline().rstrip()

def f(n):
	(x1, y1) = (x - n * a, y - n * b)
	return n + min(x1 / b, y1 / a)

def ternary_search():
	(l, r) = (0, int(min(x / a, y / b)))
	while r - l > 3:
		m1 = int(l + (r - l) / 3)
		m2 = int(r - (r - l) / 3)
		if f(m1) < f(m2):
			l = m1
		else:
			r = m2
	ans1 = 0
	for i in range(l, r + 1):
		ans1 = max(ans1, int(f(i)))
	return ans1
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	mx = min(x // a, y // b)
	ans = mx
	if a == b:
		print(min(x, y) // a)
		continue
	print(ternary_search())


t = int(input())
for _ in range(t):
	(x, y, a, b) = map(int, input().split())
	ans = max(min(x // a, y // b), min(x // b, y // a))
	d = 0
	if a != b:
		d = max(x * a - y * b, x * b - y * a) // abs(b * b - a * a)
	for k in range(max(d - 2, 0), d + 2):
		A = x - k * a
		B = y - k * b
		if A >= 0 and B >= 0:
			ans = max(ans, k + min(A // b, B // a))
	for k in range(max(d - 2, 0), d + 2):
		A = y - k * a
		B = x - k * b
		if A >= 0 and B >= 0:
			ans = max(ans, k + min(A // b, B // a))
	print(ans)


from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt

def geti():
	return map(int, input().strip().split())

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

def getis():
	return map(str, input().strip().split())

def getls():
	return list(map(str, input().strip().split()))

def gets():
	return input().strip()

def geta():
	return int(input())

def print_s(s):
	stdout.write(s + '\n')

def solve():
	for _ in range(geta()):
		(x, y, a, b) = geti()
		if x < y:
			(x, y) = (y, x)
		if a < b:
			(a, b) = (b, a)
		ans = -1
		start = 1
		end = x
		while start <= end:
			mid = (start + end) // 2
			if mid * a <= x and mid * b <= y and (x - mid * a >= y - mid * b):
				ans = mid
				start = mid + 1
			else:
				end = mid - 1
		if ans != -1:
			x -= ans * a
			y -= ans * b
		else:
			ans = 0
		start = 1
		end = x
		res = 0
		while start <= end:
			mid = (start + end) // 2
			if mid & 1 == 0:
				temp = mid // 2
				if temp * (a + b) <= x and temp * (a + b) <= y:
					res = mid
					start = mid + 1
				else:
					end = mid - 1
			else:
				temp1 = mid // 2
				temp2 = mid - temp1
				if temp1 * a + temp2 * b <= x and temp1 * b + temp2 * a <= y:
					res = mid
					start = mid + 1
				elif temp1 * b + temp2 * a <= x and temp1 * a + temp2 * b <= y:
					res = mid
					start = mid + 1
				else:
					end = mid - 1
		print(ans + res)
solve()


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	A = min(a, b)
	b = max(a, b)
	a = A
	dif2 = b - a
	A = min(x, y)
	y = max(x, y)
	x = A
	cnt = 0
	dif1 = y - x
	if dif1 > dif2 and dif1 > 0 and (dif2 > 0):
		cnt += min(x // a, y // b, dif1 // dif2)
		x -= a * cnt
		y -= b * cnt
	cr = min(x // (a + b), y // (a + b))
	cnt += 2 * cr
	x -= cr * (a + b)
	y -= cr * (a + b)
	if x >= a and y >= b:
		cnt += 1
	print(cnt)


import sys
IS_INTERACTIVE = False
input = input
if not IS_INTERACTIVE:
	(*data,) = sys.stdin.read().split('\n')[::-1]

	def input():
		return data.pop()

def fprint(*args, **kwargs):
	print(*args, **kwargs, flush=True)

def eprint(*args, **kwargs):
	print(*args, **kwargs, file=sys.stderr)

def getk(x, y, a, b):
	lo = 0
	hi = y // b + 1
	while lo != hi:
		mid = (lo + hi) // 2
		if a * (x - mid * a) >= (y - mid * b) * b:
			lo = mid + 1
		else:
			hi = mid
	return max(min(lo - 1, x // a, y // b), 1)
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if x < y:
		(x, y) = (y, x)
	if a < b:
		(a, b) = (b, a)
	if a == b:
		print(y // b)
	else:
		cnt = 0
		while y >= b and x >= a:
			k = getk(x, y, a, b)
			x -= k * a
			y -= k * b
			cnt += k
			if x < y:
				(x, y) = (y, x)
		print(cnt)


import heapq, math
from collections import defaultdict, deque
from os import getcwd
import sys, os.path
if os.path.exists('C:/Users/Dhanush/Desktop/cp/input.txt'):
	sys.stdout = open('C:/Users/Dhanush/Desktop/cp/output.txt', 'w')
	sys.stdin = open('C:/Users/Dhanush/Desktop/cp/input.txt', 'r')
input = sys.stdin.readline

def check(n):
	s = 0
	e = n
	while s <= e:
		s1 = (s + e) // 2
		s2 = n - s1
		x1 = s1 * a + s2 * b
		y1 = s1 * b + s2 * a
		if x1 <= x and y1 <= y:
			return True
		if x1 > x:
			if a > b:
				e = s1 - 1
			else:
				s = s1 + 1
		elif b > a:
			e = s1 - 1
		else:
			s = s1 + 1
	return False
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	s = 0
	e = 10 ** 9
	ans = 0
	while s <= e:
		mid = (s + e) // 2
		if check(mid):
			ans = mid
			s = mid + 1
		else:
			e = mid - 1
	print(ans)


def g(x, y, a, b):
	if a == b:
		return min(x, y) // a
	f = lambda u: max(0, min((x - a * u) // b, (y - b * u) // a))
	umax = min(x // a, y // b)
	o = max(0, f(0), umax + f(umax))
	u_cont = (a * x - b * y) // (a ** 2 - b ** 2)
	if 0 < u_cont < umax:
		o = max(o, u_cont + f(u_cont))
	if 0 < u_cont + 1 < umax and u_cont * (a ** 2 - b ** 2) != a * x - b * y:
		o = max(o, u_cont + 1 + f(u_cont + 1))
	return o
t = int(input())
for _ in range(t):
	(x, y, a, b) = [int(w) for w in input().split()]
	print(g(x, y, a, b))


def solve():
	(x, y, a, b) = map(int, input().split())
	if a == b:
		return min(x, y) // a
	if a < b:
		(a, b) = (b, a)
	d = a - b
	(lo, hi) = (0, max(x // b, y // b))
	while lo < hi:
		m = (lo + hi + 1) // 2
		L = (a * m - y + d - 1) // d
		R = (x - b * m) // d
		if R < L or L > m or R < 0:
			hi = m - 1
		else:
			lo = m
	return lo
for _ in range(int(input())):
	print(solve())


import sys
input = sys.stdin.readline

def solve():
	(x, y, a, b) = map(int, input().split())
	if b * b - a * a != 0:
		zz = (y * b - x * a) // (b * b - a * a)
		if zz >= 0:
			x1 = x - a * zz
			y1 = y - b * zz
			if x1 >= 0 and y1 >= 0:
				w = min(x1 // b, y1 // a)
				xx = x1 - b * w
				yy = y1 - a * w
				print(zz + w + min(xx // a, yy // b))
				return
	w = min(x // a, y // b)
	xx = x - a * w
	yy = y - b * w
	r = w + min(xx // b, yy // a)
	w = min(x // b, y // a)
	xx = x - b * w
	yy = y - a * w
	r = max(r, w + min(xx // a, yy // b))
	print(r)
for i in range(int(input())):
	solve()


n = int(input())
for _ in range(n):
	(x, y, a, b) = [int(i) for i in input().split()]
	if a == b:
		print(min(x // a, y // a))
	else:
		n2 = (y * a - x * b) // (a ** 2 - b ** 2)
		n1 = (x * a - y * b) // (a ** 2 - b ** 2)
		if n2 < 0:
			print(min(x // a, y // b))
		elif n1 < 0:
			print(min(x // b, y // a))
		else:
			ans1 = min((x - a * n1) // b, (y - b * n1) // a) + n1
			ans2 = min((y - a * n2) // b, (x - b * n2) // a) + n2
			print(max(ans1, ans2))


def main():
	t = int(input())
	INF = float('inf')
	for _ in range(t):
		(x, y, a, b) = map(int, input().split())
		if a == b:
			ans = min(x // a, y // a)
			print(ans)
			continue
		p = (b * y - a * x) / (b * b - a * a)
		r = (b * x - a * y) / (b * b - a * a)
		ans = 0
		if p > 0 and r > 0:
			p = round(p)
			r = round(r)
			for dp in range(-2, 3):
				for dr in range(-2, 3):
					np = p + dp
					nr = r + dr
					if np < 0 or nr < 0:
						continue
					if a * np + b * nr <= x and b * np + a * nr <= y:
						ans = max(ans, np + nr)
		else:
			T = [(x // a, 0), (0, x // b), (y // b, 0), (0, y // a)]
			for (p, r) in T:
				for dp in range(-2, 3):
					for dr in range(-2, 3):
						np = p + dp
						nr = r + dr
						if np < 0 or nr < 0:
							continue
						if a * np + b * nr <= x and b * np + a * nr <= y:
							ans = max(ans, np + nr)
		print(ans)
main()


def solve():
	(x, y, a, b) = map(int, input().split())
	if a == b:
		return min(x, y) // a
	if x // b <= y // a and x // a <= y // b:
		return max(x // b, x // a)
	if x // b >= y // a and x // a >= y // b:
		return max(y // a, y // b)
	if a < b:
		(a, b) = (b, a)
	d = a * a - b * b
	(m, n) = ((a * x - b * y) // d, (-b * x + a * y) // d)
	best = 0
	for mm in (m - 1, m, m + 1):
		for nn in (n - 1, n, n + 1):
			if mm < 0 or nn < 0 or a * mm + b * nn > x or (a * nn + b * mm > y):
				continue
			best = max(best, mm + nn)
	return best
for _ in range(int(input())):
	print(solve())


from math import *
from collections import Counter
from bisect import *
import sys
import fractions

def solve():
	(x, y, a, b) = [int(s) for s in input().split(' ')]
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(x // a)
		return
	xy_diff = y - x
	ab_diff = b - a
	take = xy_diff // ab_diff
	take = min([take, x // a, y // b])
	ans = take
	x -= take * a
	y -= take * b
	together = x // (a + b)
	ans += 2 * together
	x -= together * (a + b)
	y -= together * (a + b)
	ans += min(x // a, y // b)
	print(ans)
t = int(input())
for _ in range(t):
	solve()


S = sorted
for s in [*open(0)][1:]:
	(x, y, a, b) = map(int, s.split())
	(x, y) = S((x, y))
	(a, b) = S((a, b))
	try:
		s = a + b
		A = k = min((y - x) // (b - a), x // a)
		x -= a * k
		y -= b * k
		k = min(x, y) // s
		A += 2 * k
		(y, x) = S((x - k * s, y - k * s))
		print(A + 1 - (x < b or y < a))
	except:
		print(x // a)


for _ in range(int(input())):
	(x, y, a, b) = list(map(int, input().split()))
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	(d, d1, v) = (y - x, b - a, 0)
	if d > d1:
		q = 10 ** 18
		if d1 != 0:
			q = d // d1
		v1 = min(q, x // a, y // b)
		v += v1
		(x, y) = (x - a * v1, y - b * v1)
	(val1, val2) = (2 * min(x // (a + b), y // (a + b)), 0)
	q1 = (x - a) // (a + b)
	q2 = (y - b) // (a + b)
	if min(x // a, y // b) != 0:
		val2 = 1 + 2 * min(q1, q2)
	print(v + max(val1, val2))


def f(x, y, a, b):
	tmp = x - y
	t = a - b
	if a == b:
		return y // a
	if y < tmp // t * b:
		return y // b
	Res = tmp // t
	y -= tmp // t * b
	x = y + tmp % t
	Res += y // (a + b) * 2
	x -= (a + b) * (y // (a + b))
	y %= a + b
	Res += min(x // a, y // b)
	return Res
for m in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	(x, y) = (max(x, y), min(x, y))
	(a, b) = (max(a, b), min(a, b))
	print(f(x, y, a, b))


def add_solve(x, y, a, b):
	res = 0
	(alpha, beta) = (x // (a + b), y // (a + b))
	res += 2 * min(alpha, beta)
	x = x - min(alpha, beta) * (a + b)
	y = y - min(alpha, beta) * (a + b)
	if x < y:
		(x, y) = (y, x)
	if y < a:
		return res
	elif x < b:
		return res
	elif x >= b and y >= a:
		return res + 1

def solve():
	(x, y, a, b) = [int(i) for i in input().split()]
	if a == b:
		print(min(x // a, y // a))
		return
	if a > b:
		(a, b) = (b, a)
	if x > y:
		(x, y) = (y, x)
	if y < b or x < a:
		print(0)
		return
	res1 = (y - x) // (b - a)
	res2 = y // b
	res3 = x // a
	result = 0
	tmp = min(res1, res2, res3)
	result += tmp
	y -= b * tmp
	x -= a * tmp
	result += add_solve(x, y, a, b)
	print(result)
	return
for t in range(int(input())):
	solve()


ts = int(input())
for case in range(0, ts):
	(x, y, a, b) = [int(p) for p in input().split()]
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(min(x // a, y // b))
		continue
	res = 0
	lo = 1
	hi = 1000000000
	while lo <= hi:
		mid = (lo + hi) // 2
		r1 = x - a * mid
		r2 = y - a * mid
		dif = b - a
		if r1 >= 0 and r2 >= 0 and (r1 // dif + r2 // dif >= mid):
			res = mid
			lo = mid + 1
		else:
			hi = mid - 1
	print(res)


def Solve():
	(x, y, a, b) = [int(val) for val in input().split()]
	if a > b:
		t = a
		a = b
		b = t
	if a == b:
		ans = min(int(x / a), int(y / a))
		print(ans)
		return
	low = 0
	high = int(1000000000.0)
	ans = -1
	while high >= low:
		mid = int((low + high) / 2)
		tx = x - a * mid
		ty = y - a * mid
		dif = b - a
		rem = int(tx / dif) + int(ty / dif)
		if tx >= 0 and ty >= 0 and (rem >= mid):
			ans = mid
			low = mid + 1
		else:
			high = mid - 1
	print(ans)
t = int(input())
for _ in range(t):
	Solve()


import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
read = lambda : map(int, input().split())
O = []
for _ in range(int(input())):
	(x, y, a, b) = read()
	if a == b:
		O.append(str(min(x, y) // a))
		continue
	if a < b:
		(a, b) = (b, a)
	d = a - b
	L = [0, (x + y) // (a + b) + 1]
	while L[1] - L[0] > 1:
		M = sum(L) // 2
		xv = a * M - x
		yv = y - b * M
		L[d * (yv // d) < xv or yv < 0 or xv > M * d] = M
	O.append(str(L[0]))
print('\n'.join(O))


import sys
import getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
(yes, no) = ('YES', 'NO')
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def minus_one(arr):
	return [x - 1 for x in arr]

def minus_one_matrix(mrr):
	return [[x - 1 for x in row] for row in mrr]

def possible(p, q, a, b, x, y):
	if x < 0 or y < 0:
		return False
	return x * a + y * b <= p and x * b + y * a <= q

def solve_(x, y, a, b):
	if a == b:
		return min(x // a, y // a)
	(p, q, a, b) = (x, y, a, b)
	(p, q) = sorted([p, q])
	(a, b) = sorted([a, b])
	x = (a * q - b * p) / (a * a - b * b)
	y = (a * p - b * q) / (a * a - b * b)
	if x <= 0 or y <= 0:
		return max(0, min(p // a, q // b), min(p // b, q // a))
	xx = int(x)
	yy = int(y)
	maxres = xx + yy
	assert possible(p, q, a, b, xx, yy) or possible(p, q, a, b, yy, xx)
	for i in list(range(100)) + [p, q, a, b, math.gcd(p, q), math.gcd(a, b), abs(a - b), abs(p - q)]:
		xx = int(x) + i
		yy = int((q - x * b) / a)
		if possible(p, q, a, b, xx, yy) or possible(p, q, a, b, yy, xx):
			maxres = max(maxres, xx + yy)
		xx = int(x) + i
		yy = int((q - x * a) / b)
		if possible(p, q, a, b, xx, yy) or possible(p, q, a, b, yy, xx):
			maxres = max(maxres, xx + yy)
		yy = int(y) + i
		xx = int((p - y * b) / a)
		if possible(p, q, a, b, xx, yy) or possible(p, q, a, b, yy, xx):
			maxres = max(maxres, xx + yy)
		yy = int(y) + i
		xx = int((p - y * a) / b)
		if possible(p, q, a, b, xx, yy) or possible(p, q, a, b, yy, xx):
			maxres = max(maxres, xx + yy)
	return maxres
for case_num in range(int(input())):
	(x, y, a, b) = list(map(int, input().split()))
	res = solve(x, y, a, b)
	print(res)


def solve(x, y, a, b):
	(x, y) = (min(x, y), max(x, y))
	(a, b) = (min(a, b), max(a, b))
	ans1 = x // a
	ans2 = y // b
	if ans1 <= ans2:
		return ans1
	max_possible = (x + y) // (a + b)
	k = (y - x) // (b - a)
	co2 = (max_possible - k) // 2
	co1 = (max_possible + k) // 2
	max_ans = 0
	store_ans1 = 0
	store_ans2 = 0
	for ans1 in range(max(0, co1 - 1), co1 + 2):
		for ans2 in range(max(0, co2 - 1), co2 + 2):
			if ans1 * a + ans2 * b <= x and ans2 * a + ans1 * b <= y:
				max_ans = max(max_ans, ans1 + ans2)
				store_ans1 = ans1
				store_ans2 = ans2
	return max_ans
t = int(input())
for i in range(t):
	(x, y, a, b) = [int(x) for x in input().split()]
	print(solve(x, y, a, b))


def solve(x, y, a, b):
	(x, y) = sorted([x, y])
	(a, b) = sorted([a, b])
	d1 = y - x
	d2 = b - a
	d3 = b + a
	if d2 == 0:
		return x // a
	if y * a > x * b:
		return x // a
	r1 = d1 // d2
	x -= r1 * a
	y -= r1 * b
	r2 = x // d3
	x -= r2 * d3
	y -= r2 * d3
	result = r1 + 2 * r2
	if x >= a and y >= b:
		result += 1
	return result
T = int(input())
for _ in range(T):
	(x, y, a, b) = [int(z) for z in input().split()]
	result = solve(x, y, a, b)
	print(result)


import math
from collections import defaultdict
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
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')
t = int(input())

def primeFactors(n):
	ans = 0
	while n % 2 == 0:
		ans += 1
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			ans += 1
			n = n // i
	if n > 2:
		ans += 1
	return ans
for i in range(t):
	(n, m, a, b) = map(int, input().split())
	val = (n + m) // (a + b)
	if a == b:
		print(min(n // a, m // a))
	else:
		l = 0
		r = val
		while l < r:
			k = (l + r) // 2
			val1 = (n - k * b) // (a - b)
			f1 = 0
			if a - b < 0:
				if n - k * b >= 0:
					val1 = 0
				else:
					val1 = math.ceil((n - k * b) / (a - b))
					f1 = 1
			val2 = (m - k * a) // (b - a)
			f2 = 0
			if b - a < 0:
				if m - k * a >= 0:
					val2 = 0
				else:
					val2 = math.ceil((m - k * a) / (b - a))
					f2 = 1
			poss = 1
			if f1 == 0 and f2 == 0:
				req = min(val1, val2)
			elif f1 == 1 and f2 == 0:
				if val2 >= val1:
					req = val1
				else:
					poss = 0
			elif f1 == 0 and f2 == 1:
				if val1 >= val2:
					req = val2
				else:
					poss = 0
			elif f1 == 1 and f2 == 1:
				req = max(val1, val2)
			if poss == 0:
				req = -1
			if req >= 0 and req <= k:
				l = k
				if r == l + 1:
					k = r
					val1 = (n - k * b) // (a - b)
					f1 = 0
					if a - b < 0:
						if n - k * b >= 0:
							val1 = 0
						else:
							val1 = math.ceil((n - k * b) / (a - b))
							f1 = 1
					val2 = (m - k * a) // (b - a)
					f2 = 0
					if b - a < 0:
						if m - k * a >= 0:
							val2 = 0
						else:
							f2 = 1
							val2 = math.ceil((m - k * a) / (b - a))
					poss = 1
					if f1 == 0 and f2 == 0:
						req = min(val1, val2)
					elif f1 == 1 and f2 == 0:
						if val2 >= val1:
							req = val1
						else:
							poss = 0
					elif f1 == 0 and f2 == 1:
						if val1 >= val2:
							req = val2
						else:
							poss = 0
					elif f1 == 1 and f2 == 1:
						req = max(val1, val2)
					if poss == 0:
						req = -1
					if req >= 0 and req <= k:
						l = r
					else:
						r = l
			else:
				r = k - 1
		print(l)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(x, y, a, b) = [int(i) for i in input().split()]
	(x, y) = (min(x, y), max(x, y))
	(a, b) = (min(a, b), max(a, b))
	lo = 0
	hi = 10 ** 9
	if b == a:
		print(x // a)
		continue
	while lo <= hi:
		mid = (lo + hi) // 2
		if x < a * mid:
			hi = mid - 1
			continue
		maxi = (x - a * mid) // (b - a)
		maxi = min(maxi, mid)
		req = mid - (y - a * mid) // (b - a)
		if maxi >= req:
			ans = mid
			lo = mid + 1
		else:
			hi = mid - 1
	print(ans)


from math import ceil
global x, y, a, b

def check(k):
	global x, y, a, b
	temp = ceil((y - k * a) / (b - a))
	return x - k * b >= 0 and (x - k * b) // (a - b) >= temp

def f(X, Y, A, B):
	global x, y, a, b
	x = min(X, Y)
	y = max(X, Y)
	a = max(A, B)
	b = min(A, B)
	if a == b:
		return x // a
	(hi, lo) = (10 ** 9, 0)
	while lo <= hi:
		m = (lo + hi) // 2
		if check(m):
			lo = m + 1
		else:
			hi = m - 1
	return lo - 1
for i in range(int(input())):
	(a, b, c, d) = map(int, input().strip().split())
	print(f(a, b, c, d))


import math
t = int(input())
for i in range(t):
	n = input()
	(x, y, a, b) = n.split(' ')
	x = int(x)
	y = int(y)
	a = int(a)
	b = int(b)
	if a == b:
		print(min(x, y) // a)
	elif max(x, y) // max(a, b) >= min(x, y) // min(a, b):
		print(min(x, y) // min(a, b))
	else:
		m = (b * x - a * y) / (b * b - a * a)
		n = (a * x - b * y) / (a * a - b * b)
		if m >= 0 and n >= 0:
			ans = max(min(x // a, y // b), min(x // b, y // a), math.floor(m) + math.floor(n))
			nm = math.ceil(m)
			nn = math.floor(n)
			if a * nn + b * nm <= x and a * nm + b * nn <= y:
				ans = max(ans, nm + nn)
			nnm = math.floor(m)
			nnn = math.ceil(n)
			if a * nnn + b * nnm <= x and a * nnm + b * nnn <= y:
				ans = max(ans, nnm + nnn)
			print(ans)
		else:
			print(max(min(x // a, y // b), min(x // b, y // a)))


import math
for i in range(int(input())):
	(x, y, a, b) = list(map(int, input().split()))
	if a == b:
		print(int(min(x, y) / a))
		continue
	(l, r) = (0, 10 ** 9 + 100)
	if a < b:
		(a, b) = (b, a)
	while r - l > 1:
		m = (l + r) // 2
		right = int(math.floor((x - m * b) * 1.0 / (a - b)))
		left = int(math.ceil((y - m * a) * 1.0 / (b - a)))
		if max(left, 0) <= min(right, m):
			l = m
		else:
			r = m
	print(l)


t = int(input())
for i in range(t):
	(x, y, p, q) = map(int, input().split())
	(x, y, p, q) = (max(x, y), min(x, y), max(p, q), min(p, q))
	if x / y > p / q:
		print(int(y / q))
	elif p == q:
		print(int(y / q))
	else:
		ans = int((x - y) / (p - q))
		x = x - p * ans
		y = y - q * ans
		ans2 = int(y / (p + q))
		x = x - (p + q) * ans2
		y = y - (p + q) * ans2
		ans3 = 0
		while x >= p and y >= q:
			x = x - p
			y = y - q
			(x, y) = (max(x, y), min(x, y))
			ans3 = ans3 + 1
		print(ans + ans2 * 2 + ans3)


import os, sys
from io import BytesIO, IOBase

def check(mid, x, y, a, b):
	r = (x - b * mid) // (a - b)
	l = (a * mid - y + a - b - 1) // (a - b)
	if l > r or l > mid or r < 0:
		return 0
	return 1

def main():
	for _ in range(int(input())):
		(x, y, a, b) = map(int, input().split())
		if a < b:
			(a, b) = (b, a)
		if x < y:
			(x, y) = (y, x)
		if a == b:
			print(max(min(x // a, y // b), min(x // b, y // a)))
			continue
		(hi, lo, ans) = (10 ** 9, 0, 0)
		while hi >= lo:
			mid = (hi + lo) // 2
			if check(mid, x, y, a, b):
				lo = mid + 1
				ans = mid
			else:
				hi = mid - 1
		print(ans)
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')
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a < b:
		(a, b) = (b, a)
	if x < y:
		(x, y) = (y, x)
	take = min(x // a, y // b)
	x -= a * take
	y -= b * take
	diff = a - b
	if not take:
		print(0)
		continue
	ans = take
	if diff:
		can_take = (x + y) // (a + b)
		target_for_x = can_take * a
		need_to_add = target_for_x - x
		transfer = need_to_add // diff
		x += transfer * diff
		y -= transfer * diff
		if need_to_add >= 0:
			if y >= 0:
				ans = max(ans, take + min(x // a, y // b))
			if y - diff >= 0:
				ans = max(ans, take + min((x + diff) // a, (y - diff) // b))
	print(ans)


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: max(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

def check(n, a, b, x, y):
	z = int(math.ceil((n * b - x) / (b - a)))
	z1 = (y - a * n) // (b - a)
	if z > n:
		return False
	if z1 < 0:
		return False
	if z <= z1:
		return True
	return False
for ik in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x // a, y // b))
		continue
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	st = 0
	end = 10 ** 9
	ans = st
	while st <= end:
		mid = (st + end) // 2
		if check(mid, a, b, x, y) == True:
			ans = mid
			st = mid + 1
		else:
			end = mid - 1
	print(ans)


import sys, math, heapq
from collections import defaultdict, deque
input = sys.stdin.readline

def solve(x, y, a, b, m):
	v = min((x - m * b) // a, (y - m * a) // b)
	return v

def solve1(x, y, a, b, m):
	v = min((x - m * a) // b, (y - m * b) // a)
	return v
T = int(input())
for _ in range(T):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x // a, y // a))
	else:
		beg = (x - y) // (a - b)
		end = (x + y) // (a + b)
		n = max((beg + end) // 2, 0)
		m = solve1(x, y, a, b, n)
		val = 0
		if m >= 0:
			val = max(val, n + m)
		m = max((end - beg) // 2, 0)
		n = solve(x, y, a, b, m)
		if n >= 0:
			val = max(val, n + m)
		print(val)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	else:
		if a < b:
			(a, b) = (b, a)
		(left, right) = (0, (x + y) // (a + b))
		while left < right:
			mid = right - (right - left) // 2
			L = max(0, (a * mid - y + a - b - 1) // (a - b))
			R = min(mid, (x - b * mid) // (a - b))
			if L <= R:
				left = mid
			else:
				right = mid - 1
		print(left)


for _ in range(int(input())):
	(x, y, a, b) = [int(u) for u in input().split()]
	(a, b) = (max(a, b), min(a, b))
	if a == b:
		print(min(x, y) // a)
		continue
	N_max = (x + y) // (a + b)
	N_min = 0
	N = 0
	while N_max >= N_min:
		N = N_min + (N_max - N_min) // 2
		n1 = min((x - N * b) // (a - b), N)
		n2 = max(-((y - a * N) // (a - b)), 0)
		if n2 > n1:
			N_max = N - 1
		else:
			max_N = N
			N_min = N + 1
	print(max_N)


from bisect import *
from heapq import *
import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))

def solve2(x, y, a, b):
	ans = 0
	target_max = max(a, b)
	target_min = min(a, b)
	while True:
		if x < y:
			(x, y) = (y, x)
		if x < target_max or y < target_min:
			break
		x -= target_max
		y -= target_min
		ans += 1
	return ans

def solve(x, y, a, b):
	if a == b:
		return min(x, y) // a
	ans = min(min(x, y) // min(a, b), max(x, y) // max(a, b))
	i1 = (x * b - y * a) // (b * b - a * a)
	j1 = (x - b * i1) // a
	i2 = (y * b - x * a) // (b * b - a * a)
	j2 = (y - a * i2) // b
	print(i1, j1)
	print(i2, j2)
	if i1 <= 0 or j1 <= 0:
		i1 = 0
		j1 = 0
	if i2 <= 0 or j2 <= 0:
		i2 = 0
		j2 = 0
	ans = max(ans, max(i1 + j1, i2 + j2))
	return ans

def solve3(x, y, a, b):
	if a == b:
		return min(x, y) // a
	ans = 0
	target_max = max(a, b)
	target_min = min(a, b)
	if x < y:
		(x, y) = (y, x)
	if max(x, y) < target_max or min(x, y) < target_min:
		return ans
	max_t = min(x // target_max, y // target_min)
	t = min(max_t, (x - y - 1) // (target_max - target_min))
	x -= target_max * t
	y -= target_min * t
	ans = t
	if max(x, y) < target_max or min(x, y) < target_min:
		return ans
	t = y // (a + b)
	temp_ans = t * 2
	x -= (a + b) * t
	y -= (a + b) * t
	temp_ans += min(x // target_max, y // target_min)
	ans += temp_ans
	return ans
T = int(input())
for _ in range(T):
	(x, y, a, b) = get_ints()
	print(solve3(x, y, a, b))


def solve():
	(x, y, a, b) = map(int, input().split())
	if a == b:
		return min(x // a, y // a)
	if a > b:
		(a, b) = (b, a)
	(L, H) = (0, min(x // a, y // a))
	while L < H:
		M = L + H + 1 >> 1
		v = (x - a * M) // (b - a)
		u = (y - a * M) // (b - a)
		if v + u < M:
			H = M - 1
		else:
			L = M
	return L
for i in range(int(input())):
	print(solve())


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	if a > b:
		(a, b) = (b, a)
	low = 0
	high = (x + y) // (a + b) + 1
	while high - low > 1:
		n = (low + high) // 2
		if max(0, (n * b - x - 1) // (b - a) + 1) <= min(n, (y - n * a) // (b - a)):
			low = n
		else:
			high = n
	print(low)


cases = int(input())
L = []
for _ in range(cases):
	L.append(list(map(int, input().split())))
for i in range(cases):
	(x, y, a, b) = L[i]
	c = 0
	if a == b:
		print(min(x, y) // a)
		continue
	if a < b:
		(a, b) = (b, a)
	if x < y:
		(x, y) = (y, x)
	while x > y and x > 0 and (y > 0):
		t = max(1, min(min(x // a, y // b), (x - y) // (a - b)))
		c += t
		x -= t * a
		y -= t * b
	if x < 0 or y < 0:
		x += a
		y += b
		c -= 1
	(x, y) = (y, x)
	t = -1
	while t != 0:
		t = x // (2 * a)
		c += 2 * t
		x -= t * (a + b)
		y -= t * (a + b)
	for _ in range(2):
		if x < y:
			(x, y) = (y, x)
		if x >= a and y >= b:
			c += 1
			x -= a
			y -= b
	print(c)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
t = 1
while t <= T:
	(x, y, a, b) = map(int, input().split())
	ans = 0
	if x < y:
		(y, x) = (x, y)
	if a < b:
		(b, a) = (a, b)
	if a == b:
		print(y // a)
		t += 1
		continue
	change = (x - y) // (a - b)
	if y // b < change:
		print(y // b)
		t += 1
		continue
	ans = change
	x -= change * a
	y -= change * b
	coup = y // (a + b)
	ans += coup * 2
	x -= coup * (a + b)
	y -= coup * (a + b)
	if x >= a and y >= b:
		ans += 1
	print(ans)
	t += 1


def test():
	(x, y, a, b) = [int(_) for _ in input().split()]
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	(l, r) = (0, 1000000001)
	while l < r:
		flag = False
		m = (l + r + 1) // 2
		(ux, uy) = (x - m * a, y - m * a)
		if ux >= 0 and uy >= 0:
			if a == b:
				flag = True
			elif ux // (b - a) + uy // (b - a) >= m:
				flag = True
		if flag == True:
			l = m
		else:
			r = m - 1
	print(l)
for tc in range(int(input())):
	test()


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x, y) // a)
		continue
	if a < b:
		(b, a) = (a, b)
	(l, r, ans) = (0, (x + y) // (a + b), -1)
	while l <= r:
		m = (l + r) // 2
		i = max(0, (a * m - y + a - b - 1) // (a - b))
		j = min(m, (x - b * m) // (a - b))
		if i <= j:
			(l, ans) = (m + 1, m)
		else:
			r = m - 1
	print(ans)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]

def solve(X, Y, A, B):
	if A == B:
		return min(X, Y) // A
	if A < B:
		(A, B) = (B, A)
	if X < Y:
		(X, Y) = (Y, X)
	x = X
	y = Y
	t1 = min((x - y) // (A - B), x // A, y // B)
	x -= A * t1
	y -= B * t1
	n = t1
	t2 = min(x, y) // (A + B)
	x -= (A + B) * t2
	y -= (A + B) * t2
	n += t2 * 2
	while True:
		if x >= y and x >= A and (y >= B):
			x -= A
			y -= B
			n += 1
		elif x <= y and x >= B and (y >= A):
			x -= B
			y -= A
			n += 1
		else:
			break
	return n
T0 = int(input())
for _ in range(T0):
	(X, Y, A, B) = map(int, input().split())
	print(solve(X, Y, A, B))


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
for _ in range(ii()):
	(x, y, a, b) = il()
	d1 = max(a, b)
	d2 = min(a, b)
	if d1 == d2:
		print(min(x, y) // d1)
		continue
	(x, y) = (min(x, y), max(x, y))
	d = min((y - x) // (d1 - d2), y // d1, x // d2)
	ans = d
	y -= d * d1
	x -= d * d2
	d = min(x // (d1 + d2), y // (d1 + d2))
	ans += 2 * d
	y -= d * (d1 + d2)
	x -= d * (d1 + d2)
	if x >= a and y >= b or (x >= b and y >= a):
		ans += 1
	print(ans)


for _ in range(int(input())):
	(x, y, a, b) = map(int, input().split())
	if a == b:
		print(min(x // a, y // a))
	else:
		t = abs(x - y)
		t2 = abs(a - b)
		k1 = t // t2
		mi = min(a, b)
		ma = max(a, b)
		miel = min(x, y)
		mael = max(x, y)
		res = 0
		k2 = miel // mi
		k3 = mael // ma
		tt = min(k1, k2, k3)
		miel -= tt * mi
		mael -= tt * ma
		res += tt
		if k1 == 0:
			if abs(t2 - t) < t2:
				if miel - mi > 0 and mael - ma > 0:
					res += 1
					miel -= mi
					mael -= ma
		tot = mi + ma
		h1 = miel // tot
		h2 = mael // tot
		hh = min(h1, h2)
		res += hh * 2
		miel -= hh * tot
		mael -= hh * tot
		t1 = max(min(mael // ma, miel // mi), min(mael // mi, miel // ma))
		res += t1
		print(res)


t = int(input())
for _ in range(t):
	(x, y, a, b) = list(map(int, input().split()))
	if a == b:
		print(min(x, y) // a)
		continue
	p = (a * x - b * y) / (a ** 2 - b ** 2)
	q = (b * x - a * y) / (b ** 2 - a ** 2)
	p = int(p)
	q = int(q)
	ans = max(min(x // a, y // b), min(x // b, y // a))
	for i in range(p - 5, p + 5):
		for j in range(q - 5, q + 5):
			if i >= 0 and j >= 0:
				if x - a * i - j * b >= 0:
					if y - a * j - b * i >= 0:
						ans = max(ans, i + j)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192

def dbg(*args, **kwargs):
	_print('\x1b[95m', end='')
	_print(*args, **kwargs)
	_print('\x1b[0m', end='')

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')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())

def solve():
	(x, y, a, b) = mpint()
	max_c = min(x // a, y // b)
	max_d = min(x // b, y // a)
	r1 = x - a * max_c
	b1 = y - b * max_c
	r2 = x - a * max_d
	b2 = y - b * max_d
	cramer = 0
	if a * a - b * b != 0:
		cc = (x * a - b * y) // (a * a - b * b)
		dd = (a * y - x * b) // (a * a - b * b)
		for (i, j) in ((0, 0), (0, 1), (1, 0), (1, 1)):
			c0 = max(0, cc + i)
			d0 = max(0, dd + j)
			if a * c0 + b * d0 <= x and b * c0 + a * d0 <= y:
				cramer = max(cramer, c0 + d0)
			c0 = max(0, cc - i)
			d0 = max(0, cc - j)
			if a * c0 + b * d0 <= x and b * c0 + a * d0 <= y:
				cramer = max(cramer, c0 + d0)
	return max(max_c + (r1 >= b and b1 >= a), max_d + (r2 >= a and b2 >= b), cramer)

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1538/problem/G'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		dbg = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG == 3:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
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')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(c1, c2, a, b) = map(int, input().split())
	if a == b:
		print(min(c1, c2) // a)
		continue
	if c1 < c2:
		(c1, c2) = (c2, c1)
	if a > b:
		(a, b) = (b, a)
	l = 0
	r = 10 ** 10
	while r - l != 1:
		m = (l + r) // 2
		x = c1 - a * m
		y = c2 - a * m
		if x >= 0 and y >= 0 and (x // (b - a) + y // (b - a) >= m):
			l = m
		else:
			r = m
	print(l)


import sys
input = sys.stdin.readline

def solve():
	(x, y, a, b) = map(int, input().split())
	w = min(x // a, y // b)
	xx = x - a * w
	yy = y - b * w
	r = w + min(xx // b, yy // a)
	w = min(x // b, y // a)
	xx = x - b * w
	yy = y - a * w
	r = max(r, w + min(xx // a, yy // b))
	if b * b - a * a != 0:
		z = (y * b - x * a) // (b * b - a * a)
		for zz in range(z - 1, z + 2):
			if zz < 0:
				continue
			x1 = x - a * zz
			y1 = y - b * zz
			if x1 < 0 or y1 < 0:
				continue
			w = min(x1 // a, y1 // b)
			xx = x1 - a * w
			yy = y1 - b * w
			r = max(r, zz + w + min(xx // b, yy // a))
			w = min(x1 // b, y1 // a)
			xx = x1 - b * w
			yy = y1 - a * w
			r = max(r, zz + w + min(xx // a, yy // b))
	print(r)
for i in range(int(input())):
	solve()


import sys
for _ in range(int(input())):
	(x, y, a, b) = map(int, sys.stdin.readline().split())
	if a == b:
		print(min(x, y) // a)
		continue
	ans = 0
	(x, y) = (max(x, y), min(x, y))
	(a, b) = (max(a, b), min(a, b))
	if b * x > a * y:
		x = int(a * y / b)
	xx = (a * x - b * y) // (a * a - b * b)
	yy = (a * y - b * x) // (a * a - b * b)
	ans = xx + yy
	yy1 = (y - b * xx) // a
	xx1 = (x - b * yy) // a
	ans = max(ans, xx + yy1, xx1 + yy)
	print(ans)


for i in range(int(input())):
	(x, y, a, b) = list(map(int, input().split()))
	(x, y) = sorted([x, y])
	(a, b) = sorted([a, b])
	c = min(x // a, y // b)
	if a == b:
		d = x // (a + b)
		x -= d * (a + b)
		y -= d * (a + b)
		c = max(c, 2 * d + min(x // a, y // b))
	else:
		(x0, y0) = (x, y)
		d = x0 // (a + b)
		x0 -= d * (a + b)
		y0 -= d * (a + b)
		c = max(c, 2 * d + min(x0 // a, y0 // b))
		d = (y - x) // (b - a)
		x -= d * a
		y -= d * b
		if x >= 0 and y >= 0:
			e = min(x, y) // (a + b) * 2
			x -= e // 2 * (a + b)
			y -= e // 2 * (a + b)
			if x >= a and y >= b:
				e += 1
			c = max(c, d + e)
	print(c)


t = int(input())

def good(m, x, y, a, b):
	(a, b) = (max(a, b), min(a, b))
	if m * b <= y and m * a <= x:
		return True
	if m * a <= y and m * b <= x:
		return True
	if x <= m * a and y <= m * a:
		s = (x - m * b) // (a - b)
		e = (m * a - y) / (a - b)
		return s >= e

def maxi(x, y, a, b):
	if a == b:
		return min(x // a, y // a)
	r = x + y + 2
	l = 0
	while r - l > 1:
		m = (r + l) // 2
		if good(m, x, y, a, b):
			l = m
		else:
			r = m
	return l
for _ in range(t):
	(x, y, a, b) = [int(x) for x in input().split()]
	print(maxi(x, y, a, b))


import sys
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	(x, y, a, b) = map(int, stdin.readline().split())
	if a == b:
		print(min(x // a, y // a))
		continue
	if a > b:
		(a, b) = (b, a)
	l = 0
	r = 10 ** 10
	while r - l != 1:
		m = (l + r) // 2
		xrem = x - a * m
		yrem = y - a * m
		if xrem >= 0 and yrem >= 0 and (xrem // (b - a) + yrem // (b - a) >= m):
			l = m
		else:
			r = m
	print(l)


import math
import sys
from collections import deque
import time
input = sys.stdin.readline
mod = 10 ** 9 + 7

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
for _ in range(inp()):
	(n, m, a, b) = invr()
	if a != b:
		u = (a * n - b * m) / (a * a - b * b)
		v = (n - a * u) / b
	else:
		u = -1
		v = -1
	if u > 0 and v > 0:
		if u + v <= max(min(n / a, m / b), min(n / b, m / a)):
			print(max(min(n / a, m / b), min(n / b, m / a)))
		else:
			c = math.ceil(u)
			d = int(v)
			if c * a + d * b <= n and c * b + d * a <= m:
				print(c + d)
				continue
			c = int(u)
			d = math.ceil(v)
			if c * a + d * b <= n and c * b + d * a <= m:
				print(c + d)
				continue
			print(max(0, int(u) + int(v)))
	else:
		u = -1
		v = -1
		print(int(max(u + v, min(n / a, m / b), min(n / b, m / a))))


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
b = []
vis = []
tot = 0

def dfs(root):
	global tot, vis, gp
	for child in gp[root]:
		if vis[child] == 0:
			tot += 1
			vis[child] = 1
			dfs(child)
pre = [[] for i in range(3)]

def check(x, y, a, b, mid):
	temp1 = x - mid * a
	temp2 = y - mid * a
	if temp1 < 0 or temp2 < 0:
		return False
	if temp1 // (b - a) + temp2 // (b - a) < mid:
		return False
	return True

def hnbhai(tc):
	(x, y, a, b) = sd()
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(min(x, y) // a)
		return
	(low, high) = (0, 1000 * 1000 * 1000)
	ans = 0
	while low <= high:
		mid = (low + high) // 2
		if check(x, y, a, b, mid):
			low = mid + 1
			ans = mid
		else:
			high = mid - 1
	print(ans)
for _ in range(sb()):
	hnbhai(_ + 1)


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys

def input():
	return sys.stdin.readline().rstrip()

def getN():
	return int(input())

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

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

def getArray(intn):
	return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
INF = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]

def f(x, y, a, b, mid):
	o1 = x - mid * a
	o2 = y - mid * a
	if o1 < 0 or o2 < 0:
		return False
	if o1 // (b - a) + o2 // (b - a) < mid:
		return False
	return True
T = getN()
for _ in range(T):
	(x, y, a, b) = getNM()
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(min(x, y) // a)
		continue
	(l, r) = (0, 10 ** 12)
	ans = 0
	while abs(r - l) > 1:
		mid = (l + r) // 2
		if f(x, y, a, b, mid):
			l = mid
			ans = mid
		else:
			r = mid
	print(ans)


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()
import bisect, string, math, time, functools, random, fractions
from bisect import *
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range
R = range

def I():
	return int(input())

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

def LI_():
	return [int(i) - 1 for i in input().split()]

def AI():
	return map(int, open(0).read().split())

def S_():
	return input()

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

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

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def NLI(n):
	return [[int(i) for i in input().split()] for i in range(n)]

def NLI_(n):
	return [[int(i) - 1 for i in input().split()] for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RLI(n=8, a=1, b=10):
	return [random.randint(a, b) for i in range(n)]

def RI(a=1, b=10):
	return random.randint(a, b)

def INP():
	N = 10
	n = random.randint(1, N)
	a = RLI(n, 0, n - 1)
	return (RI(0, 100), RI(1, 100), RI(1, 100))

def Rtest(T):
	(case, err) = (0, 0)
	for i in range(T):
		inp = INP()
		a1 = naive(*inp)
		a2 = solve(*inp)
		if a1 != a2:
			print(inp)
			print('naive', a1)
			print('solve', a2)
			err += 1
		case += 1
	print('Tested', case, 'case with', err, 'errors')

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
alp = [chr(ord('a') + i) for i in range(26)]

def gcj(c, x):
	print('Case #{0}:'.format(c + 1), x)
show_flg = False
show_flg = True

def primeFactor(N):
	(i, n) = (2, N)
	ret = {}
	(d, sq) = (2, 99)
	while i <= sq:
		k = 0
		while n % i == 0:
			(n, k, ret[i]) = (n // i, k + 1, k + 1)
		if k > 0 or i == 97:
			sq = int(n ** (1 / 2) + 0.5)
		if i < 4:
			i = i * 2 - 1
		else:
			(i, d) = (i + d, d ^ 6)
	if n > 1:
		ret[n] = 1
	return ret

def divisor(n):
	div = [1]
	for (i, j) in primeFactor(n).items():
		div = [i ** k * d for d in div for k in range(j + 1)]
	return div

def PrimeNumSet(N):
	M = int(N ** 0.5)
	seachList = [i for i in range(2, N + 1)]
	primes = []
	while seachList:
		if seachList[0] > M:
			break
		primes.append(seachList[0])
		tmp = seachList[0]
		seachList = [i for i in seachList if i % tmp != 0]
	return primes + seachList

def LCM(b, mo=10 ** 9 + 7):
	prs = PrimeNumSet(max(b))
	M = dict(zip(prs, [0] * len(prs)))
	for i in b:
		dc = primeFactor(i)
		for (j, k) in dc.items():
			M[j] = max(M[j], k)
	r = 1
	for (j, k) in M.items():
		if k != 0:
			r *= pow(j, k, mo)
			r %= mo
	return r

def extgcd(x, y):
	if y == 0:
		return (1, 0)
	(r0, r1, s0, s1) = (x, y, 1, 0)
	while r1 != 0:
		(r0, r1, s0, s1) = (r1, r0 % r1, s1, s0 - r0 // r1 * s1)
	return (s0, (r0 - s0 * x) // y, x * s0 + y * (r0 - s0 * x) // y)

def crt(rems, mods):
	n = len(rems)
	if n != len(mods):
		return NotImplemented
	(x, d) = (0, 1)
	for (r, m) in zip(rems, mods):
		(a, b, g) = extgcd(d, m)
		(x, d) = ((m * b * x + d * a * r) // g, d * (m // g))
		x %= d
	for (r, m) in zip(rems, mods):
		if r != x % m:
			return (-1, d)
	return (x, d)

def intsqrt(x):
	if x < 0:
		return NotImplemented
	rt = int(x ** 0.5) - 1
	while (rt + 1) ** 2 <= x:
		rt += 1
	return rt
ans = 0
for i in range(I()):
	a = 0
	(x, y, a, b) = LI()
	(a, b) = (max(a, b), min(a, b))
	c = a - b
	if a == b:
		print(min(x, y) // a)
		continue
	(l, r) = (0, 10 ** 9 + 10)
	while r - l > 1:
		m = l + r >> 1
		s = x - m * b
		t = y - m * b
		if s // c + t // c >= m and s >= 0 and (t >= 0):
			l = m
		else:
			r = m
	print(l)


import sys
input = sys.stdin.readline

def I():
	return input().strip()

def II():
	return int(input().strip())

def LI():
	return [*map(int, input().strip().split())]
import copy, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, combinations, groupby
from operator import itemgetter
for _ in range(II()):
	(x, y, a, b) = LI()
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	if a == b:
		print(min(x, y) // a)
		continue
	ans = 0
	while True:
		changed = False
		temp = math.floor((y - x) / (b - a)) + 1
		if temp > 0:
			tempx = x - temp * a
			tempy = y - temp * b
			if tempx > 0 and tempy > 0:
				ans += temp
				(x, y) = (tempy, tempx)
				changed = True
		if changed:
			if a + b <= x:
				add = a + b
				num = x // add
				x = x - num * add
				y = y - num * add
				ans += num * 2
			if a <= x and b <= y:
				ans += 1
		else:
			ans += min(x // a, y // b)
		break
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, m, x, y) = [int(x) for x in input().split()]
	if x > y:
		(x, y) = (y, x)
	diff = y - x
	if x > min(n, m) or y > max(n, m):
		print(0)
		continue
	(start, end) = (1, 10 ** 9 + 1)

	def isvalid(mid):
		a = n - mid * x
		b = m - mid * x
		if a < 0 or b < 0:
			return False
		if diff == 0:
			return True
		return a // diff + b // diff >= mid
	while start <= end:
		mid = (start + end) // 2
		if isvalid(mid):
			ans = mid
			start = mid + 1
		else:
			end = mid - 1
	print(ans)


def possible(a, b, x, y, total):
	if a == b:
		return total * a <= x
	if y < a * total:
		return False
	m = min((y - a * total) // (b - a), total)
	return a * m + b * (total - m) <= x
t = int(input())
for _ in range(t):
	(x, y, a, b) = map(int, input().split())
	if y < x:
		(x, y) = (y, x)
	if b < a:
		(a, b) = (b, a)
	(left, right) = (0, y // a)
	if possible(a, b, x, y, right):
		print(right)
		continue
	while right - left > 1:
		mid = (left + right) // 2
		if possible(a, b, x, y, mid):
			left = mid
		else:
			right = mid
	print(left)


from sys import stdin, stdout
import collections, heapq, bisect, math
input = stdin.readline

def rint():
	return int(input())

def rstr():
	return input().strip()

def rlstr():
	return list(input().strip().split())

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

def main():
	(x, y, a, b) = rlint()
	res = 0
	if x < y:
		(x, y) = (y, x)
	if a < b:
		(a, b) = (b, a)
	if a == b:
		print(y // b)
		return
	z = (x - y) // (a - b)
	if y // b < z:
		print(y // b)
		return
	res += z
	x = x - z * a
	y = y - z * b
	z = y // (a + b)
	res += z * 2
	x = x - z * (a + b)
	y = y - z * (a + b)
	if x >= a and y >= b:
		res += 1
	print(res)
for _ in range(rint()):
	main()


from collections import defaultdict
import math

def main():
	for _ in range(int(input())):
		(x, y, a, b) = list(map(int, input().split()))
		l = 0
		r = 10 ** 9 + 100
		if a == b:
			print(min(x, y) // a)
		else:
			if a < b:
				(a, b) = (b, a)
			while r > l + 1:
				ans = (r + l) // 2
				right = math.floor((x - b * ans) / (a - b))
				left = math.ceil((y - a * ans) / (b - a))
				if max(left, 0) <= min(right, ans):
					l = ans
				else:
					r = ans
			print(l)

def SumOfExpOfFactors(a):
	fac = 0
	lis = SortedList()
	if not a & 1:
		lis.add(2)
	while not a & 1:
		a >>= 1
		fac += 1
	for i in range(3, int(a ** 0.5) + 1, 2):
		if not a % i:
			lis.add(i)
		while not a % i:
			a //= i
			fac += 1
	if a != 1:
		lis.add(a)
		fac += 1
	return (fac, lis)
div = [0] * 1000001

def NumOfDivisors(n):
	for i in range(1, n + 1):
		for j in range(i, n + 1, i):
			div[j] += 1

def primes1(n):
	sieve = [True] * (n // 2)
	for i in range(3, int(n ** 0.5) + 1, 2):
		if sieve[i // 2]:
			sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
	return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]

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

class Graph:

	def __init__(self):
		self.Graph = defaultdict(list)

	def addEdge(self, u, v):
		self.Graph[u].append(v)
		self.Graph[v].append(u)

	def DFSUtil(self, v, visited):
		visited.add(v)
		for neighbour in self.Graph[v]:
			if neighbour not in visited:
				self.DFSUtil(neighbour, visited)

	def DFS(self, v):
		visited = set()
		self.DFSUtil(v, visited)

	def BFS(self, s):
		visited = set()
		queue = []
		queue.append(s)
		visited.add(s)
		while queue:
			s = queue.pop(0)
			for i in self.Graph[s]:
				if i not in visited:
					queue.append(i)
					visited.add(i)

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
main()


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(x, y, a, b) = map(int, input().split())
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	MAX = x // (a + b)
	MIN = 0
	MAXX = MAX
	MINX = MIN
	while MAX > MIN + 1:
		mid = (MAX + MIN) // 2
		x2 = x - mid * (a + b)
		y2 = y - mid * (a + b)
		if y2 * a > b * x2:
			MAX = mid
		else:
			MIN = mid
	ANS = 0
	for p in range(MIN - 10, MAX + 11):
		if MINX <= p <= MAXX:
			x2 = x - p * (a + b)
			y2 = y - p * (a + b)
			ANS = max(ANS, p * 2 + min(x2 // a, y2 // b))
	print(ANS)


import bisect
import collections
import functools
import heapq
import itertools
import math
import random
import sys
input = sys.stdin.readline
ri = lambda : int(input())
rf = lambda : list(map(float, input().split()))
rl = lambda : list(map(int, input().split()))
rs = lambda : input().rstrip()
MOD = 10 ** 9 + 7
INF = math.inf

def solve_case():
	(x, y, a, b) = rl()
	if x > y:
		(x, y) = (y, x)
	if a > b:
		(a, b) = (b, a)
	xy_diff = y - x
	ab_diff = b - a
	if ab_diff == 0:
		print(x // a)
		return
	ans = take = min([xy_diff // ab_diff, x // a, y // b])
	x -= take * a
	y -= take * b
	together = x // (a + b)
	ans += 2 * together
	x -= together * (a + b)
	y -= together * (a + b)
	ans += min(x // a, y // b)
	print(ans)
T = ri()
for ti in range(1, T + 1):
	solve_case()


import sys
pl = 1
sys.setrecursionlimit(10 ** 5)
if pl:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('outpt.txt', 'w')

def li():
	return [int(xxx) for xxx in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

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

def ff():
	sys.stdout.flush()
t = fi()

def check(x, y):
	if a * x + b * y <= c and b * x + a * y <= d and (x >= 0) and (y >= 0):
		return x + y
	return 0
while t > 0:
	t -= 1
	(c, d, a, b) = mi()
	ans = 0
	if a != b:
		x = (a * c - b * d) // (a ** 2 - b ** 2)
		y = (a * d - b * c) // (a ** 2 - b ** 2)
		for i in range(-2, 3):
			for j in range(-2, 3):
				ans = max(ans, check(x + i, y + j))
	p = [c // a, 0]
	q = [0, c // b]
	r = [d // b, 0]
	s = [0, d // a]
	for i in range(-2, 3):
		for j in range(-2, 3):
			ans = max(ans, check(p[0] + i, p[1] + j))
			ans = max(ans, check(q[0] + i, q[1] + j))
			ans = max(ans, check(r[0] + i, r[1] + j))
			ans = max(ans, check(s[0] + i, s[1] + j))
	print(ans)