There is an infinite board of square tiles. Initially all tiles are white.

Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board.

Vova wants to color such a set of tiles that:

  they would form a rectangle, consisting of exactly $a+b$ colored tiles;  all tiles of at least one color would also form a rectangle. 

Here are some examples of correct colorings:

 [Image] 

Here are some examples of incorrect colorings:

 [Image] 

Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?

It is guaranteed that there exists at least one correct coloring.


-----Input-----

A single line contains two integers $a$ and $b$ ($1 \le a, b \le 10^{14}$) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.


-----Output-----

Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly $a$ tiles red and exactly $b$ tiles blue.

It is guaranteed that there exists at least one correct coloring.


-----Examples-----
Input
4 4

Output
12

Input
3 9

Output
14

Input
9 3

Output
14

Input
3 6

Output
12

Input
506 2708

Output
3218



-----Note-----

The first four examples correspond to the first picture of the statement.

Note that for there exist multiple correct colorings for all of the examples.

In the first example you can also make a rectangle with sides $1$ and $8$, though its perimeter will be $18$ which is greater than $8$.

In the second example you can make the same resulting rectangle with sides $3$ and $4$, but red tiles will form the rectangle with sides $1$ and $3$ and blue tiles will form the rectangle with sides $3$ and $3$.

Source: codeforces | Difficulty: HARD
Tags: Number theory

Sorting

Mathematics

Complete search


Solutions:
(a, b) = map(int, input().split())
(s1, s2, s3) = (a ** 0.5, b ** 0.5, (a + b) ** 0.5)
m = a + b
ans = 0
for i in range(1, int(s3) + 1):
	if i <= s1 and a % i == 0:
		m = min(m, a // i)
	if i <= s2 and b % i == 0:
		m = min(m, b // i)
	if (a + b) % i == 0:
		d = (a + b) // i
		if d >= m:
			ans = (i + d) * 2
print(ans)


from math import sqrt
(a, b) = map(int, input().split())
(a, b) = (min(a, b), max(a, b))
rec_size = []
for i in range(1, int(sqrt(b)) + 1):
	if i <= int(sqrt(a)):
		if a % i == 0:
			rec_size.append([i, a // i])
		elif b % i == 0:
			rec_size.append([i, b // i])
	elif b % i == 0:
		rec_size.append([i, b // i])
ok = False
for i in range(int(sqrt(a + b)), 0, -1):
	if (a + b) % i == 0:
		for rec in rec_size:
			if i >= rec[0] and (a + b) // i >= rec[1]:
				ok = True
				break
	if ok:
		break
print(2 * (i + (a + b) // i))


from math import sqrt
(a, b) = map(int, input().split())
c = a + b
sa = int(sqrt(a))
sb = int(sqrt(b))
sc = int(sqrt(c))
m = c
ans = 0
for i in range(1, sc + 1):
	if i <= sa and a % i == 0:
		m = min(m, a // i)
	if i <= sb and b % i == 0:
		m = min(m, b / i)
	if c % i == 0:
		tmp = c / i
		if tmp >= m:
			ans = (i + tmp) * 2
print(int(ans))


import sys, bisect as bi
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))

def anp(x, y):
	vd = [1, x] + ([] if x % 2 else [2, x // 2])
	for i in range(3, int(x ** 0.5) + 1):
		if x % i == 0:
			vd.append(i)
			if i != x // i:
				vd.append(x // i)
	vd.sort()
	an = 2 * x + 2 * y + 2
	for i in range(len(dv)):
		cr = dv[i]
		p = bi.bisect(vd, cr)
		p -= 1
		if (x + y) // cr >= x // vd[p]:
			an = min(an, 2 * (cr + (x + y) // cr))
	return an
(a, b) = I()
x = a + b
dv = [1, x] + ([] if x % 2 else [2, x // 2])
for i in range(3, int(x ** 0.5) + 1):
	if x % i == 0:
		dv.append(i)
		if i != x // i:
			dv.append(x // i)
print(min(anp(a, b), anp(b, a)))


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
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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=300006, 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)

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

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data

def find(a):
	ans = set()
	n = a
	for i in range(1, int(a ** 0.5) + 1):
		if n % i == 0:
			ans.add(i)
			ans.add(n // i)
	ans = sorted(ans)
	return ans
(a, b) = map(int, input().split())
e = find(a + b)
e1 = find(a)
e2 = find(b)
ans = 2 * (a + b + 1)
for i in range(len(e)):
	b1 = binarySearchCount(e1, len(e1), e[i])
	if b1 != 0:
		r = e1[b1 - 1]
		if (a + b) // e[i] >= a // e1[b1 - 1]:
			ans = min(ans, 2 * (e[i] + (a + b) // e[i]))
	b1 = binarySearchCount(e2, len(e2), e[i])
	if b != 0:
		r = e2[b1 - 1]
		if (a + b) // e[i] >= b // e2[b1 - 1]:
			ans = min(ans, 2 * (e[i] + (a + b) // e[i]))
print(ans)


(a, b) = map(int, input().split())
ad = []
for i in range(1, a + 1):
	if i * i > a:
		break
	if a % i == 0:
		ad.append(i)
		if i * i != a:
			ad.append(a // i)
bd = []
for i in range(1, b + 1):
	if i * i > b:
		break
	if b % i == 0:
		bd.append(i)
		if i * i != b:
			bd.append(b // i)
ab = a + b
abd = []
for i in range(1, ab + 1):
	if i * i > ab:
		break
	if ab % i == 0:
		abd.append(i)
		if i * i != ab:
			abd.append(ab // i)
ad.sort()
bd.sort()
abd.sort()
ai = -1
bi = -1
r = int(400000000000000.0)
for d in abd:
	while ai + 1 < len(ad) and ad[ai + 1] <= d:
		ai += 1
	while bi + 1 < len(bd) and bd[bi + 1] <= d:
		bi += 1
	h = ab // d
	if ai >= 0 and a // ad[ai] <= h or (bi >= 0 and b // bd[bi] <= h):
		r = min(r, h + d)
print(r * 2)


import math
import time
D = False

def b_search(lst, num, row, col, ab):
	H = len(lst) - 1
	L = 0
	while L <= H:
		M = (L + H) // 2
		if D:
			print(lst[M], row, ab / lst[M], col)
		if D:
			print('cond:', lst[M] <= row, num / lst[M] <= col)
		if lst[M] <= row and num / lst[M] <= col:
			return True
		if lst[M] > row:
			H = M - 1
		else:
			L = M + 1
	return False

def binary_search(lst1, a, lst2, b, row, col, ab):
	if b_search(lst1, a, row, col, ab):
		return True
	return b_search(lst2, b, row, col, ab)

def divisors(num):
	rtn = []
	for i in range(1, math.ceil(math.sqrt(num)) + 1):
		if num % i == 0:
			rtn.append(i)
	return rtn

def sol():
	(a, b) = [int(x) for x in input().split(' ')]
	ab = a + b
	if D:
		print('')
	if D:
		print('a, b, ab:', a, b, ab)
	div_a = divisors(a)
	div_b = divisors(b)
	div_ab = divisors(ab)
	if D:
		print('div_a: ' + ', '.join([str(x) for x in div_a]))
		print('div_b: ' + ', '.join([str(x) for x in div_b]))
		print('div_ab: ' + ', '.join([str(x) for x in div_ab]))
	for i in range(len(div_ab) - 1, -1, -1):
		row = div_ab[i]
		col = int(ab / row)
		if D:
			print('\n* Trying')
		if D:
			print('row, col:', row, col)
		ans = binary_search(div_a, a, div_b, b, row, col, ab)
		if ans:
			return 2 * (row + col)
if D:
	start = time.time()
ans = int(sol())
print(ans)
if D:
	end = time.time()
	print(end - start)


import math
(a, b) = [int(x) for x in input().split()]
area = a + b
t = int(math.sqrt(area))
sa = int(math.sqrt(a))
sb = int(math.sqrt(b))
D = []
DA = []
DB = []
for i in range(1, t + 1):
	if area % i == 0:
		if i * i != area:
			D.append(i)
			D.append(area // i)
		else:
			D.append(i)
for i in range(1, sa + 1):
	if a % i == 0:
		if i * i != a:
			DA.append(i)
			DA.append(a // i)
		else:
			DA.append(i)
for i in range(1, sb + 1):
	if b % i == 0:
		if i * i != b:
			DB.append(i)
			DB.append(b // i)
		else:
			DB.append(i)
DA.sort()
DB.sort()
D.sort()
start = (len(D) + 1) // 2 - 1
div = len(D)

def closestdiv(t, D):
	low = 0
	high = len(D) - 1
	while high - low > 1:
		guess = (high + low) // 2
		if D[guess] > t:
			high = guess
		else:
			low = guess
	if D[high] <= t:
		return high
	else:
		return low
while start > -1:
	t = D[start]
	s = D[-start - 1]
	if DA[-closestdiv(t, DA) - 1] <= s:
		print(2 * t + 2 * s)
		break
	elif DB[-closestdiv(t, DB) - 1] <= s:
		print(2 * t + 2 * s)
		break
	start -= 1


inp = input()
inp = inp.split()
a = int(inp[0])
b = int(inp[1])
ma = a + b
mx = ans = 1e+19
k = int(ma ** 0.5)
i = 1
while i <= k:
	if a % i == 0:
		mx = min(mx, a / i)
	if b % i == 0:
		mx = min(mx, b / i)
	if ma % i == 0 and ma / i >= mx:
		ans = min(ans, 2 * (i + ma / i))
	i += 1
print(int(ans))


from math import sqrt
lens = [0 for _ in range(1000000)]

def solve(a, b):
	k = 0
	for i in range(1, int(sqrt(b)) + 2):
		if b % i == 0:
			lens[k] = i
			k += 1
	ans = 2 * (a + b) + 2
	x = a + b
	l = 0
	for i in range(1, int(sqrt(x)) + 2):
		if x % i == 0:
			while l + 1 < k and lens[l + 1] <= i:
				l += 1
			if b * i <= x * lens[l]:
				ans = min(ans, (i + x // i) * 2)
	return ans
(a, b) = map(int, input().split())
print(min(solve(a, b), solve(b, a)))


import sys
input = sys.stdin.readline
from math import sqrt
(a, b) = map(int, input().split())
x = a + b
A = []
for i in range(1, int(sqrt(a)) + 1):
	if a % i == 0:
		A.append(i)
B = []
for i in range(1, int(sqrt(b)) + 1):
	if b % i == 0:
		B.append(i)
for i in range(int(sqrt(x)) + 1, 0, -1):
	if x % i == 0:
		y = x // i
		flag = 0
		for m in A:
			if m <= i and a // m <= y:
				flag = 1
				break
		for m in B:
			if m <= i and b // m <= y:
				flag = 1
				break
		if flag:
			print(i * 2 + y * 2)
			break


from math import sqrt
(a, b) = map(int, input().split())
if a > b:
	(a, b) = (b, a)
u = []
sqa = int(sqrt(a))
sqb = int(sqrt(b))
for i in range(1, sqb + 1):
	if i <= sqa and a % i == 0:
		u.append((i, a // i))
	elif b % i == 0:
		u.append((i, b // i))
ok = False
sqab = int(sqrt(a + b))
for i in range(sqab, 0, -1):
	if (a + b) % i == 0:
		k = (a + b) // i
		for j in u:
			if i >= j[0] and k >= j[1]:
				ok = True
				break
	if ok:
		break
print(2 * (i + k))


import sys
from collections import Counter, defaultdict, deque
mod = 10 ** 9 + 7
INF = float('inf')

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

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

def make_divisors(n):
	divisors = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			divisors.append(i)
			if i != n // i:
				divisors.append(n // i)
	divisors.sort()
	return divisors
(a, b) = inpl()
st = []
for z in [a, b]:
	tmp = make_divisors(z)
	for i in range(len(tmp) // 2 + 1):
		s = tmp[i]
		t = z // s
		st.append([s, t])
ttt = make_divisors(a + b)
for i in range(len(ttt) // 2 + 1)[::-1]:
	y = ttt[i]
	x = (a + b) // y
	for (s, t) in st:
		if x >= t and y >= s:
			print(2 * (x + y))
			quit()


import bisect
import sys
input = sys.stdin.readline
(a, b) = map(int, input().split())
su = a + b
f1 = []
for i in range(1, int(su ** (1 / 2)) + 1):
	if su % i == 0:
		f1.append(i)
ans = float('inf')
f2 = []
for i in range(1, int(a ** (1 / 2)) + 1):
	if a % i == 0:
		f2.append(i)
for i in f1:
	xx = bisect.bisect(f2, i)
	if xx != 0:
		d2 = f2[xx - 1]
		if su // i >= a // d2:
			ans = min(ans, 2 * (i + su // i))
(a, b) = (b, a)
f2 = []
for i in range(1, int(a ** (1 / 2)) + 1):
	if a % i == 0:
		f2.append(i)
for i in f1:
	xx = bisect.bisect(f2, i)
	if xx != 0:
		d2 = f2[xx - 1]
		if su // i >= a // d2:
			ans = min(ans, 2 * (i + su // i))
print(ans)


import sys
import itertools as it
import bisect as bi
import math as mt
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, m) = I()
a = []
b = []
c = []
for i in range(1, int(n ** 0.5) + 1):
	if n % i == 0:
		a.append(i)
for i in range(1, int(m ** 0.5) + 1):
	if m % i == 0:
		b.append(i)
ne = n + m
for i in range(1, int(ne ** 0.5) + 1):
	if ne % i == 0:
		c.append(i)
ans = mt.inf
for i in c[::-1]:
	j = ne // i
	tf = 0
	for ii in a:
		if ii <= i and n // ii <= j:
			tf = 1
			break
	for jj in b:
		if jj <= i and m // jj <= j:
			tf = 1
			break
	if tf:
		ans = min(ans, 2 * (i + j))
		break
print(ans)


from math import sqrt, ceil
import bisect

def divisors(n):
	s = [1]
	for i in range(2, ceil(sqrt(n)) + 1):
		if n % i == 0:
			s.append(i)
	if len(s) == 1:
		s.append(n)
	return s
bisect_right = bisect.bisect
(a, b) = map(int, input().split())
s = a + b
k = a
diva = divisors(a)
divb = divisors(b)
divs = divisors(s)
ansA = 0
ansB = 0
diva.sort()
divb.sort()
for i in range(len(divs)):
	s = bisect_right(diva, divs[i]) - 1
	if (a + b) / divs[i] >= a / diva[s]:
		ansA = 2 * (divs[i] + (a + b) / divs[i])
for i in range(len(divs)):
	s = bisect_right(divb, divs[i]) - 1
	if (a + b) / divs[i] >= b / divb[s]:
		ansB = 2 * (divs[i] + (a + b) / divs[i])
print(int(min(ansA, ansB)))


import math
(n, m) = map(int, input().split())
k = n + m
c = int(math.sqrt(k))
a = int(math.sqrt(n))
b = int(math.sqrt(m))
ma = k
ans = 0
for i in range(1, c + 1):
	if i <= a and n % i == 0:
		ma = min(ma, n // i)
	if i <= b and m % i == 0:
		ma = min(ma, m // i)
	if k % i == 0:
		t = k // i
		if t >= ma:
			ans = (i + t) * 2
print(ans)


import math

def all_small_divs(n):
	res = [1]
	for i in range(2, int(math.sqrt(n) + 1)):
		if n % i == 0:
			res.append(i)
	return res
INF = float('inf')
(a, b) = map(int, input().split())
ab = a + b
ad = all_small_divs(a)
bd = all_small_divs(b)
abd = all_small_divs(ab)
maxa = [-1] * len(abd)
ap = len(ad) - 1
lp = len(abd) - 1
while lp >= 0 and ap >= 0:
	if ad[ap] <= abd[lp]:
		maxa[lp] = ad[ap]
		lp -= 1
	else:
		ap -= 1
maxb = [-1] * len(abd)
ap = len(bd) - 1
lp = len(abd) - 1
while lp >= 0 and ap >= 0:
	if bd[ap] <= abd[lp]:
		maxb[lp] = bd[ap]
		lp -= 1
	else:
		ap -= 1
p = [INF] * len(abd)
for i in range(len(abd)):
	x = abd[i]
	y = ab // x
	xa = maxa[i]
	ya = a // xa
	if ya <= y:
		p[i] = 2 * (x + y)
	xb = maxb[i]
	yb = b // xb
	if yb <= y:
		p[i] = min(p[i], 2 * (x + y))
print(min(p))


read_numbers = lambda : map(int, input().split())
INF = 1 << 64
(a, b) = read_numbers()
(ans, n, m) = (INF, 1, 1)
for i in range(1, int((a + b) ** 0.5 + 1)):
	if a % i == 0:
		n = i
	if b % i == 0:
		m = i
	if (a + b) % i == 0:
		second = (a + b) // i
		if a // n <= second or b // m <= second:
			ans = min(ans, 2 * (second + i))
print(ans)


import bisect
import math
import sys
input = sys.stdin.readline

def divisor(i):
	s = []
	for j in range(1, int(math.sqrt(i)) + 1):
		if i % j == 0:
			s.append(i // j)
			s.append(j)
	return sorted(set(s))
(a, b) = map(int, input().split())
c = a + b
aa = divisor(a)
bb = divisor(b)
cc = divisor(c)
aa.append(c + 5)
bb.append(c + 5)
ans = 2 * (c + 1)
for h in cc:
	ok = 0
	w = c // h
	i = bisect.bisect_left(aa, h + 0.5)
	x = aa[i - 1]
	y = a // x
	if x <= h and y <= w:
		ok = 1
	i = bisect.bisect_left(aa, w + 0.5)
	y = aa[i - 1]
	x = a // y
	if x <= h and y <= w:
		ok = 1
	i = bisect.bisect_left(bb, h + 0.5)
	x = bb[i - 1]
	y = b // x
	if x <= h and y <= w:
		ok = 1
	i = bisect.bisect_left(bb, w + 0.5)
	y = bb[i - 1]
	x = b // y
	if x <= h and y <= w:
		ok = 1
	if ok:
		ans = min(ans, 2 * (h + w))
print(ans)