# # --- Система регистрации (словарь)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
#     if i not in database:
#         database[i] = 0
#         print('OK')
#     else:
#         for k, val in database.items():
#             if val >= 0 and k == i:
#                 val += 1
#                 database[i] = val
#                 print(k + str(val))
#                 # print(k + f'{val}')

# # --- Система регистрации (правильное решение)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
#     if i in database:
#         database[i] += 1
#         print(i + str(database[i]))
#     else:
#         database[i] = 0
#         print('OK')

# # --- Single number ---
# nums = [2, 2, 1, 1, 1, 7]
# count = {}
# for i in nums:
# 	if i in count:
# 		count[i] += 1
# 	else:
# 		count[i] = 1
# for i in count:
# 	if count[i] == 1:
# 		print(i)

# # --- Persons ---
# contacts = {
#     "John Kennedy": {
#         'birthday': '29 may 1917',
#         'city': 'Brookline',
#         'phone': None,
#         'children': 3
#     },
#     "Arnold Schwarzenegger": {
#         'birthday': '30 july 1947',
#         'city': 'Gradec',
#         'phone': '555-555-555',
#         'children': 5
#     },
#     "Donald John Trump": {
#         'birthday': '14 july 1946',
#         'city': 'New York',
#         'phone': '777-777-333',
#         'children': 4
#     }
# }

# persons = list(contacts.keys())

# for person in persons:
#     print(person)
#     for data in contacts[person]:
#         print(data, contacts[person][data], sep=': ')
#     print()

balls, friends = map(int, input().split())
colours = input().lower()
i = 0
lucky = 0
while len(colours) > 0:
    for j in range(1, len(colours)):
        if colours[i] != colours[j]:
            colours = colours[1:j] + colours[j + 1:]
            lucky += 1
            break
        if j == len(colours) - 1:
            i = 1
    if i == 1:
        break
if len(colours) == 0 or lucky == friends:
    print('YES')
else:
    print('NO')


a, k = input().split()
a = [int(i) for i in a]
k = int(k)

n = 0
for i in range(len(a)):
    if n >= k: break
    max_i = i + a[i:i + k - n].index(max(a[i:i + k - n]))
    t = a.pop(max_i)
    a.insert(i, t)
    n += max_i - i

print(''.join(str(i) for i in a))


import sys
input = sys.stdin.readline
def multi_input():
    return map(int, input().split())

def array_print(arr):
    print(''.join(map(str, arr)))

n, k = multi_input()
k1 = k
n1 = n
len = 0
while n1:
    n1 = n1//10
    len +=1

a = [0]*len
i = len
while n:
    temp = n%10
    a[i-1] = temp
    n //= 10
    i-=1

i = 0
while k>0:
    max1 = a[i]
    indx = i
    for j in range(i, min(len, i+k+1)):
        # print(j)
        if a[j]>max1:
            max1 = a[j]
            indx = j

    if i!=indx:
        for j in range(i+1, indx+1):
            a[i], a[j] = a[j], a[i]
            k-=1
    i = (i+1)%len
    # array_print(a)
    if i==len-1 and k==k1:
        break

array_print(a)


n, k, l, c, d, p, nl, np = list(map(int, input().split()))

return min(k*l/nl, c*d, p/np)//n


n = int(input())

if (n+1) % 2 ==0 and (n!=0):
    print((n+1)//2)
else if n==0:
    print(0)
else:
    print(n+1)


l = list(map(int, input().split()))
n = l[0]
k = l[1]
m = input(str())
m = sorted(m)
maxx = 0
index = m[0]
Flag = 0

for i in m:
    if i == index:
        Flag += 1
    else:
        if Flag > maxx:
            maxx = Flag
        Flag = 0
        index = i
        if i == index:
            Flag += 1

if maxx > k:
    print("NO")
else:
    print("YES")


from collections import defaultdict

n, k = map(int, input().split())

colors = input()
count = defaultdict(lambda:0)

for color in colors:
    count[color] zz

print(0)


x,y,a,b=map(int, raw_input().split())
if a%x:
    ax = a-a%x+x
if a%y:
    ay = a - a%y+y

print len(set(range(ax,b+1, x))&set(range(ay,b+1,y)))


import fractions

x,y,a,b=map(int, raw_input().split())
cd = fractions.gcd(x, y)

r=x*y/cd
ar=a
if a%r:
    ar = a-a%r+r

print len(range(ar,b+1, r))


import math

if __name__ == "__main__":
    n, x, pos = map(int, input().split())
    l = 0
    r = n
    a = 0  # a&n1 -> smaller
    b = 0
    p = 1000000007
    while l < r:
        m = math.floor((l+r)/2)
        if m < pos:
            a = a + 1
            l = m + 1
        elif m > pos:
            b = b + 1
            r = m
        elif m == pos:
            l = m + 1
    n1 = x - 1
    n2 = n - x
    ans = math.factorial(n1) // math.factorial(n1-a) % p
    ans = ans * math.factorial(n2) // math.factorial(n2-b) % p
    ans = ans * math.factorial(n-a-b-1) % p
    print(ans)


n, x, p = map(input().split())
mod = 10 ** 9 + 7
ans = 1
left, right = 0, n
c1, c2 = 0, 0
while left < right:
    mid = left + (right - left) // 2
    if mid <= p:
        c1 += 1
        left = mid + 1
    else:
        c2 += 1
        right = mid
ans = 1
for i in range(1, n - c1 - c2 + 1):
    ans = ans * i % mod
c1 -= 1
p1, p2 = x - 1, n - x
for i in range(p1, p1 - c1, -1):
    ans = ans * p1 % mod
    p1 -=1
for i in range(p2, p2 - c2, -1):
    ans = ans * p2 % mod
    p2 -= 1
print(ans)


a,b,c = sorted(map(int,input().split()))
print(max(0, c - a - b + 1)))


l=list(map(int,input.split())
l.sort()
print max(0,l[2]-(l[0]+l[1]-1))


x=0
z=[]
y=int(input())
count=0
for i in range (y):
	z.append(input())
for i in z:
    if i== "++X" or i =="X++":
        count+=1
    else:
        count-=1
 print(count)


l,d,v,g,r=map(float,raw_input().split())
s,S=d/v,0.0
while True:
	S += g
	if s <= S:
		s = 0.0
		break
	S += r
	if s <= S:
		s = S-s
		break
print l/v + s


from math import floor
def summa(n):
    return (n*(n+1))/2
m,b = map(int,raw_input().split())
y = b
ans = 0
while y>=0 :
    x = (b-y)*m
    temp = summa(floor(y))*(x+1) + summa(floor(x))*(y+1)
    if temp>ans :
        ans = temp
    y -= 1
x = m*b
while x>=0 :
    y = ((-1*x)/(m))+b
    temp = summa(floor(y))*(x+1) + summa(floor(x))*(y+1)
    if temp>ans :
        ans = temp
    x -= 1
print int(ans)


def main():
    m, b = map(int, raw_input().split())
    ans = tmp = (1 + b) * b / 2
    j = 0
    for i in xrange(1, m * b + 1):
        if j == 0:
            tmp -= b * i + i * (i - 1) / 2
            b -= 1
        tmp += (1 + b) * b / 2 + (b + 1) * i
        if ans < tmp:
            ans = tmp
        j += 1
        if j == m:
            j = 0
    print ans
main()


m,b = map(lambda x:int(x),raw_input().strip().split())
sign1 = -m*b/abs(m*b)
maxs = 0
for x in range(int(b*m)+1):
	for y in range(b+1):
		if (m*y+x-m*b)*sign1>=0:
			s = (x+y)*(x+1)*(y+1)/2
			maxs = max(s,maxs)
print maxs


def count(a, b):
    return (a + 1) * (b + 1) * (a + b) / 2

m, b = map(int, raw_input().split())
foo = 0

for i in range(m * b + 1):
    if count(i, (b * m - i) / m) > foo:
        foo = count(i, (b * m - i) / m)

print foo


c,d,a,b=temp.split()
c=int(c)
d=int(d)
a=int(a)
b=int(b)
if(c<d):
    if((c*a)<b):
        print a
    else:
        print b
    exit()
cost1=0
cost2=0
cost1=c*a
cost2=(c/d)*b
c=c%d
if((c*a)<(c*b)):
    cost2+=c*a
elif(c!=0):
    cost2+=b
if(cost1<cost2):
    print cost1
else:
    print cost2


from sys import stdin
def get(n,ma):
    res = [1]
    st = 65
    if n==1:
        return res
    while st >=0:
        st-=1
        if res[-1] * n > ma:
            break
        res.append(res[-1] * n)
    return res
try:
    x,y,l,r = map(int,stdin.readline().split())
    a = get(x,r)
    b = get(y,r)
    c = set()
    for i in a:
        for j in b:
            if i + j >=l and i + j <=r:
                c.add(i+j)
    c = list(c)
    c.sort()
    ans = max(c[0]-l,r-c[-1])
    pr = l
    for i in c:
        ans = max(ans, i-pr-1)
        pr = i
    print ans
except:
    while True:
        n = 1


count = 0
x,y,l,r = map(int, raw_input().strip().split())
list1 = []
done = False
while not done:
    temp = list1[:]
    for i in range(count+1):
        a = i
        b = count -i
        ans = x**a + y**b
        if ans<=r and ans>=l:
            list1.append(ans)
    count += 1
    if temp == list1 and len(list1)!= 0:
        done = True
        break
list1 = sorted(list(set([l-1]+list1+[r+1])))
list3 = [abs(list1[n]-list1[n+1]) for n in range(len(list1)-1)]
print max(list3) - 1


#!/usr/bin/env python3
"""
Codeforces
327 A. Flipping Game

@author yamaton
@date 2015-08-05
"""

import itertools

def solve(xs):
    consecutive_zeros = max(sum(1 for _ in ite) for (i, ite) in itertools.groupby(xs) if i == 0)
    return xs.count(1) + consecutive_zeros

def main():
    n = int(input())
    xs = [int(i) for i in input().strip().split()]
    assert len(xs) == n
    result = solve(xs)
    print(result)

if __name__ == '__main__':
    main()


def main():
    n,m,a,b = map(int,input().split())
    if n<=1:
        print(min(a,b))
    else:
        nOt=n//m
        if n%m!=0:
            nOt=nOt+1
        collection = []
        for i in range(nOt,1,-1):
            first = b*i
            second = a*(n-(i*m))
            if second<0:
                second = 0
            collection.append(first+second)
        print(min(collection))

if __name__ == "__main__":
    main()


import math
n,m=[int(x) for x in input().split()]
d=math.factorial(n)
e=math.factorial(m)
f=math.gcd(d,e)
print(f)


import sys

facto=[1,1,2,6]

def factorial(n):
    for i in range(4,n+1):
        facto.append(facto[i-1]*i)

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

A,B=[int(x)for x in sys.stdin.readline().strip().split()]
factorial(max(A,B))
print(gcd(facto[A],facto[B]))


a,b= map(int, input().split())
import math
a1= math.factorial(a)
b1= math.factorial(b)
GCD = math.gcd(a1,b1)
print(GCD)


a, b = map(int, input().split())
for i in range(1, a+1):
    a = a * i
for y in range(1, b+1):
    b = b * y

while b != 0:
        a, b = b, a % b
print(a)


n, k, l, c, d, p, nl, np,=input().split()
n=int(n)
k=int(k)
l=int(l)
c=int(c)
d=int(d)
p=int(p)
nl=int(nl)
np=int(np)
print((min(k*l,c*d,p)/n)


n,k,l,c,d,p,nl,np = map(int,input().strip().split())
ans1 = (k*l)/nl
ans2 = c*d
ans3 = p/np
return min(ans1, ans2, ans3)/n


n, k, l, c, d, p, nl, np = [int(i) for i in input().split()]
print(min((k*l)//(n*nl), c*d//n, p//(n*np))


inp = []
for i in xrange(8):
    xy = map(int, raw_input().split())
    inp.append(xy)
x_set = set([i[0] for i in inp])
y_set = set([i[1] for i in inp])
if len(x_set) == 3 and len(y_set) == 3:
    x_ls = sorted(list(x_set))
    y_ls = sorted(list(y_set))
    if [x_ls[1], y_ls[1]] in inp:
        print "ugly"
    else:
        print "respectable"
else:
    print "ugly"


def strToInt(str_list):
    return map(int, str_list.split(' '))

def readInp():

    input_data = []
    for i in range(8):
        input_data.append(raw_input())

    return input_data

points = readInp()

if len(set(points)) != len(points):
    print 'ugly'
else:

    x_list = []
    y_list = []
    for x,y in map(strToInt, points):
        x_list.append(x)
        y_list.append(y)

    X_min = min(x_list)
    X_max = max(x_list)

    Y_min = min(y_list)
    Y_max = max(y_list)

    if (x_list.count(X_min) == 3) & (x_list.count(X_max) == 3) &\
    (y_list.count(Y_min) == 3) & (y_list.count(Y_max) == 3):
        print 'respectable'
    else:
        print 'ugly'


from math import *
x = [int(q) for q in input().split()]
r = x[0]
x1 = x[1]
y1 = x[2]
x2 = x[3]
y2 = x[4]

ans = math.sqrt(((x1 - x2)**2 + (y1 - y2)**2))
print(ceil(ans/2*r))


a, b, c = map(int, input().split())
x = a+b-c
y = b+c-a
z = c+a-b
if x&1 or y&1 or z&1 or x<0 or y<0 or z<0:
  print('IMPOSSIBLE')
else
  print(x//2, y//2, z//2)


n = int(input())
if n == 0:
    print(0)
elif (n+1)%2 == 0:
    print((n+1)//2)
else n != 0:
    print(n+1)


n = int(input())
if (n+1) % 2 == 0 and n !+ 0:
    print((n+1)//2)
elif n == 0:
    print(0)
else:
    print(n+1)


n=int(input())
if(n%2==0):
    if(n==0):
        print(0)
        break
    print(n+1)
else:
    print((n+1)//2)


a,b=map(int,input().split())
if b<=a:
	c=b
	# d=a
elif a<=b:
	c=a
	# d=b
y=int(abs(a-b)/2


numbers = input ()
redsock = int (numbers[0])
bluesock = int (numbers [2])
days = 0
counter = 0

while counter == 0:
    if (redsock >= 1) and (bluesock >= 1):
        days = days + 1
        redsock = (redsock - 1)
        bluesock = (bluesock - 1)
    else:
        if redsock == 0:
            days = days + (bluesock/2)
        if bluesock == 0:
            days = days + (redsock/2)
        counter = 1

return (days)


n, k = map(int, raw_input().split());
total = k * (k - 1) / 2;
if total < n - 1:
    print -1;
else:
    ans = 0;
    tmp = n- 1;
    for i in range(k - 1):
        j = k - 1 - i;
        if tmp - j >= 0:
            tmp -= j;
            ans += 1;
        if tmp == 0:
            break;
    print ans;


# encoding: utf-8

if __name__ == '__main__':
    n, k = [int(x) for x in raw_input().rstrip().split()]

    ans = 0
    pipe = 1
    splitter = range(1, k)
    while (splitter):
        if pipe >= n:
            break
        s = splitter.pop()
        ans += 1
        pipe += s

    if pipe >= n:
        print ans
    else:
        print -1


import math
sl = raw_input().split()
n = int(sl[0])
k = int(sl[1])

print int((2*k-3 - math.sqrt((3-2*k)*(3-2*k) - 8*(n-k)))/2 + 1)


#!/usr/bin/env python
# coding=utf-8
def solve(n, max_val):
    if n <= max_val:
        return 1
    return 1 + solve(n - max_val, max_val - 1)

n, k = map(int, raw_input().split())
n -= 1
k -= 1
if n > (k + 1) * k / 2:
    print -1
    exit(0)
print solve(n, k)


n = int(input())
a = list(map(int,list(input())))
lst = []
for j in a:
    for i in range(i):
    if i==2:
        lst.append(i)
    elif i==3:
        lst.append(i)
    elif i==4:
        lst.extend([2,2,3])
    elif i==5:
        lst.append(i)
    elif i==6:
        lst.extend([2,3,5])
    elif i==7:
        lst.append(i)
    elif i==8:
        lst.extend([2,2,2,7])
    elif i==9:
        lst.extend([3,3,2,2,2,7])
lst.sort(reverse=True)
print(''.join(list(map(str,lst))))


import fileinput
from math import ceil

# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
	(hy, ay, dy) = [ int(x) for x in args[0].split() ]
	(hm, am, dm) = [ int(x) for x in args[1].split() ]
	(h, a, d) = [ int(x) for x in args[2].split() ]
	return(hy, ay, dy, hm, am, dm, h, a, d)

def to_win(hy, ay, dy, hm, am, dm):
	dmgy = max(0, am - dy)
	dmgm = max(0, ay - dm)
	if dmgy == 0:
		return 0
	if dmgm == 0:
		return float('inf')
	nturns = ceil(hm / dmgm)
	return max(0, (dmgy * nturns - hy + 1))

def solve(args, verbose=False):
	(a, b, c, i, j, k, x, y, z) = proc_input(args)
	lookup = {}
	min = float('inf')
	for a_y in xrange(b, 200 + 1):
		for d_y in xrange(c, 100 + 1):
			r = (a_y - b) * y + (d_y - c) * z
			r += to_win(a, b, c, i, j, k) * x
			if min > r:
				min = r
	assert(min >= 0)
	if verbose:
		print int(min)
	return int(min)

def test():
	assert(proc_input([ '1 2 3', '4 5 6', '7 8 9' ]) == (1, 2, 3, 4, 5, 6, 7, 8, 9))
	assert(solve([ '1 2 1', '1 100 1', '1 100 100' ]) == 99)
	assert(solve([ '100 100 100', '1 1 1', '1 1 1' ]) == 0)

if __name__ == '__main__':
	from sys import argv
	if argv.pop() == 'test':
		test()
	else:
		solve(list(fileinput.input()), verbose=True)


l, r = raw_input().split()
m = len(l)
n = len(r)

l = int(l)
r = int(r)

m9 = int('9' * m)
n9 = int('9' * n)
hm = int('4' + '9' * (m - 1))
hn = int('4' + '9' * (n - 1))

ans = 0

if m == n:
    ans = max(ans, max(l * (m9 - l), r * (n9 - r)))
    if (l <= hm and hm <= r):
        ans = max(ans, hm * (m9 - hm))
else:
    if l <= hm:
        ans = max(ans, hm * (m9 - hm))
    else:
        ans = max(ans, l * (m9 - l))

    if r <= hm:
        ans = max(ans, hn * (n9 - hn))
    else:
        ans = max(ans, r * (n9 - r))

print ans


def weight(num):
    p = str(num)
    st = ""
    count=0
    for character in p:
        reflection = str(9-int(character))
        st += reflection
    if st[0]=="0":
#
#we need to eliminate all d zeroesu #from d start till a non zejro is #encountered or d string lasts den #return 0 since unidigit 0 is allowedj
#
        for r in range(1 , len(st)+1):
            if st[0:r] == ("0") * r:
                count+=1
            else:
                break
#jaisa hi pehla non zero mila break d
#loop
#max r ki value store
#ho jaayegi a mein loop ke end mein
#
        if count == len(st):
            return 0
        else:
            return ((int(st[count:])) * num)
    else:
        return ((int(st)) * num)
#
def max_weight(l , r):
    m = len(str(l))
    n=len(str(r))  #since r > l so m>=n
    p=int((int("9" * n)) / 2)
    mp=weight(p)
    ml=weight(l)
    mr=weight(r)
#
    if m==n :
        if r<p:
            return mr
        elif l>q:
            return ml
        else:
            return mp
#bich mein p aayega hi
    else:
        if r < p :
            return mr
        else:
            return mp
#
L , R = map(int , raw_input().split(" "))
print max_weight(L , R)


def weight(num):
    p = str(num)
    st = ""
    count=0
    for character in p:
        reflection = str(9-int(character))
        st += reflection
    if st[0]=="0":
#
#we need to eliminate all d zeroesu #from d start till a non zejro is #encountered or d string lasts den #return 0 since unidigit 0 is allowedj
#
        for r in range(1 , len(st)+1):
            if st[0:r] == ("0") * r:
                count+=1
            else:
                break
#jaisa hi pehla non zero mila break d
#loop
#max r ki value store
#ho jaayegi a mein loop ke end mein
#
        if count == len(st):
            return 0
        else:
            return ((int(st[count:])) * num)
    else:
        return ((int(st)) * num)
#
def max_weight(l , r):
    m = len(str(l))
    n=len(str(r))  #since r > l so m>=n
    p=int((int("9" * n)) / 2)
    q=p+1
#
    if m==n :
        if l==p or r==p or l==q or r==q:
            return weight(p)
        elif r<p:
            return weight(r)
        elif l>q:
            return weight(l)
        else:
            return weight(min((p-l) , (r-q)))
    else:
        if r < p :
            return weight(r)
        else:
            return weight(p)
#
L , R = map(int , raw_input().split(" "))
print max_weight(L , R)


def check(msg,hmsg):
    l = msg.split(hmsg[0])
    for i in l :
        if len(i)<len(hmsg[1:]):
            l.remove(i)
    for x in l:
        a=0
        for g in hmsg[1:]:
            if x.count(g)>=hmsg[1:].count(g):
                a+=1
            else:a=0
        if a:
            b=[x.index(i) for i in hmsg[1:]]
            b.sort()
            if b == [x.index(i) for i in hmsg[1:]]:
                return True
    return False
st = raw_input()
if check(st,list("hello")):
    print "YES"
else:
    print "NO"


w = input()

w = int(w)

if(w % 2 == 0):
  if(w / 2 != 1):
    e = True
else:
  e = False
  if(e == False):
    if(w % 3 == 0):
      w = w / 3
      if(w % 2 != 0):
        e = False
      else:
        e = True

if(e == True):
  print("YES")
else:
  print("NO")


def a(ans, n, pf):
    if n == 1:
        return ans
    for i in pf:
        if n % i == 0:
            m = a(ans + [i], n // i, pf[:i+1])
            if m != None:
                return m
        else:
            return None
    return None
n = int(input())
s = input()
pf1 = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
pf = [2, 6, 120, 5040]
pfo = {2:2, 6:3, 120:5, 5040:7}
summ = 1
for i in s:
    if int(i) != 0:
        summ *= pf1[int(i)-1]
for i in pf:
    if summ % i == 0:
        m = a([i], summ // i, pf[:i+1])
        if m != None:
            break
    else:
        break
m.sort(reverse = True)
for i in m:
    print(pfo[i], end = '')


import sys
import os

# Your code here

asdasdasdas


n=int(input())
a=input().split()
b={}
c={}
def skaicius(i,j):
    return a[i:j].count("0")
def skaicius1(i,j):
    return a[i:j].count("1")

def maksimumas(i,j):
    if (i,j) in b:
        return b[(i,j)]
    if j==i+1 and a[i]=="0":
        return 1
    elif j==i+1 and a[i]=="1":
        return 0
    else:
        b[(i,j-1)]=maksimumas(i,j-1)
        b[(i+1,j)]=maksimumas(i+1,j)
        if max(maksimumas(i+1,j), maksimumas(i,j-1), skaicius(i,j)-skaicius1(i,j))==maksimumas(i+1,j):
            c[(i+1,j)]=maksimumas(i+1,j)
        elif max(maksimumas(i+1,j), maksimumas(i,j-1), skaicius(i,j)-skaicius1(i,j))==maksimumas(i,j-1):
            c[(i,j-1)]=maksimumas(i,j-1)
        else:
            c[(i,j)]=skaicius(i,j)-skaicius1(i,j)
        return max(maksimumas(i+1,j), maksimumas(i,j-1), skaicius(i,j)-skaicius1(i,j))

maksimumas(0,n)
m=[i for i in c.keys() if c[i]==maksimumas(0,n)]
lo=a[m[0][0]:m[0][1]].count("0")
mo=a[m[0][0]:m[0][1]].count("1")
popp=a.count("1")-mo+lo
print(popp)


n=int(input())
if n%2==0:
    print("Mahmoud)
else:
    print("Ehab")


#print(['Mahmoud', 'Ehab'][int(input())%2])
if (int(input()%2==0):
     print("Mahmoud")
else:
     print("Ehab")


print("Mahmoud" if int(input()) % 2 == 0 : "Ehab")


def compote(lemons,apples,pears):
	for i in xrange(lemons,0,-1):
		if 2 * i <= apples and 4 * i <= pears:
			print i + 2 * i + 4 * i
			exit()
	print 0

a,b,c = map(int, raw_input().split())
compote(a,b,c)


Skip to content
Features
Business
Explore
Marketplace
Pricing
This repository
Search
Sign in or Sign up
1 3 1 shahed-shd/Online-Judge-Solutions
 Code  Issues 0  Pull requests 0  Projects 0  Insights
Online-Judge-Solutions/Codeforces/515C - Drazil and Factorial.py
a01faf7  on Mar 7, 2017
@shahed-shd shahed-shd Codeforces 515C - Drazil and Factorial.py

51 lines (40 sloc)  1.08 KB
# ==================================================
# Problem   :   515C - Drazil and Factorial
# Run time  :   0.061 sec.
# Language  :   Python 3
# ==================================================

def main():
    from sys import stdin, stdout

    # stdin = open("in.txt", "r")

    num = stdin.read().split()[1]

    ans = []

    for d in num:
        if d == '2':
            ans.append('2')
        elif d == '3':
            ans.append('3')
        elif d == '4':
            ans.append('3')
            ans.append('2')
            ans.append('2')
        elif d == '5':
            ans.append('5')
        elif d == '6':
            ans.append('5')
            ans.append('3')
        elif d == '7':
            ans.append('7')
        elif d == '8':
            ans.append('7')
            ans.append('2')
            ans.append('2')
            ans.append('2')
        elif d == '9':
            ans.append('7')
            ans.append('3')
            ans.append('3')
            ans.append('2')

    ans.sort(reverse=True)

    stdout.write(''.join(ans))

if __name__ == '__main__':
    main()
© 2018 GitHub, Inc.
Terms
Privacy
Security
Status
Help
Contact GitHub
API
Training
Shop
Blog
About
Press h to open a hovercard with more details.


from scipy.special import binom, comb
def D(m,n):
    tmp=0
    for k in range(m+1):
        print('(m,k)=(%d, %d)='%(m,k),binom(m,k))
        print('(n+k, m)=(%d, %d)='%(n+k, m), binom(n+k,m))
        print('product=', binom(m,k)*binom(n+k,m))
        tmp+=binom(m,k)*binom(n+k,m)
    print(tmp)
    return tmp
def t(m,n,k):
    print('(m,k)(n+k,m)=', binom(m,k)*binom(n+k,m))

def prob(n,k):
    p1=binom(k,3)/binom(n,3)
    p2=binom(k,2)*(n-k)/binom(n,3)
    p3=1/2*k*binom(n-k,2)/binom(n,3)
    ptot=p1+p2+p3
    return ptot
np=input()
np=np.split(' ')
n=int(np[0])
p=float(np[1])
left=0
right=n
while(left<right):
    k=(left+right)//2
    if(prob(n,k)<p):
        left=k+1
    else:
        right=k

while(prob(n,k)<p):
    k+=1

print(k)


def naiveSolve():

    return

def solve():

    return

def getP(n,x):
    # calculate for all 3 known
    if x<3:
        p3=0
    else:
        p3=(x/n)*((x-1)/(n-1))*((x-2)/(n-2))

    # calculate for 2 known
    if x<2:
        p2=0
    else:
        p2=3*(x/n)*((x-1)/(n-1))*((n-x)/(n-2))
        # discard the unknown

    # calculate for 1 known
    if x<1:
        p1=0
    else:
        p1=3*(x/n)*((n-x)/(n-1))*((n-x-1)/(n-2))

        p11=p1*(1/3)*0.5 # opponent picks the same 0 map as Johnny to discard
        p12=p1*(1/3) # opponent picks a different 0 map as Johnny to discard
        p1=p11+p12

    return p1+p2+p3

# def getP2(n,x):
#     from random import randint
#     arr=[0]*(n-x)+[1]*n
#     cnts=100000
#     succeedCnts=0
#     for _ in range(cnts):
#         a=b=c=randint(0,n-1)
#         while b==a:
#             b=randint(0,n-1)
#         while c==a or c==b:
#             c=randint(0,n-1)
#         x=arr[a]+arr[b]+arr[c] # known map
#         y=3-x
#         if y>0:
#             y-=1
#         else:
#             x-=1
#         arr2=[]
#         for __ in range(x): arr2.append(1)
#         for __ in range(y): arr2.append(0)
#         succeedCnts+=arr2[randint(0,1)]
#     return succeedCnts/cnts

def main():

    eps=0

    n,p=input().split()
    n=int(n)
    p=float(p)

    x=0
    bb=n
    while bb>0:
        while x+bb<=n and getP(n,x+bb)+eps<p:
            x+=bb
        bb//=2
    x+=1

    print(x)

    # for x in range(0,n+1):
    #     p=getP(n,x)
    #     p2=getP2(n,x)
    #     print('x:{} p:{} p2:{}'.format(x,p,p2))

    return

import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
# def readFloatArr():
#     return [float(x) for x in input().split()]

def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
    dv=defaultValFactory;da=dimensionArr
    if len(da)==1:return [dv() for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]

def queryInteractive(x):
    print('{}'.format(x))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()

inf=float('inf')
# MOD=10**9+7
# MOD=998244353

from math import gcd,floor,ceil
# from math import floor,ceil # for Python2

for _abc in range(1):
    main()


n, p = input().split()
n = int(n)
p = float(p)

gt = [1, 1, 2, 6]

def C(n, k):
    ans = 1
    for i in range(n-k+1, n+1):
        ans*=i
    return ans//gt[k]

# k la so muon hoc
def check(k):
    t = C(n-k, 3)/C(n, 3)
    return (k/n)*t+k/(n-1) >= p

l = 0
r = n-1
while l<=r:
    m = (l+r)//2
    if check(m):
        r = m - 1
    else:
        l = m + 1
print(l)


i=int(input())
xm=3+2*i-1
l=[]
for j in range (1,i+1):
    for k in range (1,k+1):
        l.append(j**2+k**2)
l.sort()
print(l[i-1])


n=int(input())
if n==1:
    print( 3)
l=[3]
while len(l)<n:
    k = l[-1]+1
    if (k // 4) == 0:
        l.append(k)
    else l.append(k+1)
print( l[-1])


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  1 11:10:33 2022

@author: Administrator
"""

import collections
for _ in range(int(input())):
    n=int(input())
    print(2*n+1)


n=int(input())
lst=[]
x=3
while(len(lst)<n):
  if(x%2==1 or x%4==0):
    if(x==4):
      y=0
    else:
      lst.append(x)
  x+=1
print(lst[n-1])


n=int(input())
dp=[]
c=0
for i in range(3,1000000000):
    if i&1:
        dp.append(i)
        c+=1
    elif i%4==0:
        dp.append(i)
        c+=1
    if c==n+1:
        print(i)
        break;


"""
https://codeforces.com/problemset/problem/1725/G
"""
rang = int(input())

def trouve_valeur_suivante(n):
    indice = 3
    k = 1
    while True:
        if indice != 2 * (2 * k + 1):
            if indice != 4:
                n -= 1
                if n == 0:
                    return indice
            indice += 1
        else:
            k += 1
            indice += 1

print(trouve_valeur_suivante(rang))


N=int(input())
import math
if N==1:
    print(3)
if N==2:
    print(5)
if N>2:
    print(math.floor(4N/3+3))


n = int(input())
a=set()
for i in range(2,n+2):
    for j in range(i-1,0,-1):
        a.add(i**2 - j**2)
l = list(a)
l.sort()
print(l[n-1])


import typing

def rit(*args) -> typing.Iterator:
    """Read input and yield split cast values.
    """
    func, funcs = int, (int, float, str)
    sep = " "
    for a in args:
        if a in funcs:
            func = a
        elif isinstance(a, str):
            sep = a
    return map(func, input().strip().split(sep))

def pit(itr: typing.Iterable, sep:str=" ") -> None:
    print(sep.join(map(str, itr)))

def rank(n):
    eps = 0.5 if n in (0, 1, 2, 4) or n % 4 == 2 else 0
    if n == 3:
        return 1
    return (n // 4 - 1) + (n - 1) // 2 + eps

def main():
    n = int(input())

    B = 1
    T = int(1e9)
    k = T // 2

    while True:
        if rank(k) == n:
            print(k)
            break
        elif n > rank(k):
            B = k
            if T - k == 1:
                k = T
            else:
                k += (T - k) // 2
        else:
            T = k
            if k - B == 1:
                k = B
            else:
                k -= (k - B) // 2

main()


######################################################################################
#------------------------------------Template---------------------------------------#
######################################################################################
import collections
import heapq
import re
import sys
import math
import itertools
import bisect
from io import BytesIO, IOBase
import os
from textwrap import indent
from typing import Counter

def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

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)
def input(): return sys.stdin.readline().rstrip("\r\n")

######################################################################################
#--------------------------------------Input-----------------------------------------#
######################################################################################

def value(): return tuple(map(int, input().split()))
def inlt(): return [int(i) for i in input().split()]
def inp(): return int(input())
def insr(): return input()
def stlt(): return [i for i in input().split()]

######################################################################################
#------------------------------------Functions---------------------------------------#
######################################################################################

def printprimesSieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    l = []
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n+1):
        if prime[p]:
            l.append(p)
            # print(p)
        else:
            continue
    return l

def isPrime(n):
    prime_flag = 0

    if n > 1:
        for i in range(2, int(math.sqrt(n)) + 1):
            if n % i == 0:
                prime_flag = 1
                break
        if prime_flag == 0:
            return True
        else:
            return False
    else:
        return False

def gcdofarray(a):
    x = 0
    for p in a:
        x = math.gcd(x, p)
    return x

def printDivisors(n):
    i = 1
    ans = []
    while i <= math.sqrt(n):
        if (n % i == 0):
            if (n / i == i):
                ans.append(i)
            else:
                ans.append(i)
                ans.append(n // i)
        i = i + 1
    ans.sort()
    return ans

def binaryToDecimal(n):
    return int(n, 2)

def countTriplets(a, n):
    s = set()
    for i in range(n):
        s.add(a[i])
    count = 0
    for i in range(n):
        for j in range(i + 1, n, 1):
            xr = a[i] ^ a[j]
            if xr in s and xr != a[i] and xr != a[j]:
                count += 1
    return int(count // 3)

def countOdd(L, R):
    N = (R - L) // 2
    if (R % 2 != 0 or L % 2 != 0):
        N += 1
    return N

def isPalindrome(s):
    return s == s[::-1]

def sufsum(a):
    test_list = a.copy()
    test_list.reverse()
    n = len(test_list)
    for i in range(1, n):
        test_list[i] = test_list[i] + test_list[i - 1]
    return test_list

def prsum(b):
    a = b.copy()
    for i in range(1, len(a)):
        a[i] += a[i - 1]
    return a

def badachotabadachota(nums):
    nums.sort()
    i = 0
    j = len(nums) - 1
    ans = []
    cc = 0
    while len(ans) != len(nums):
        if cc % 2 == 0:
            ans.append(nums[j])
            j -= 1
        else:
            ans.append(nums[i])
            i += 1
        cc += 1
    return ans

def chotabadachotabada(nums):
    nums.sort()
    i = 0
    j = len(nums) - 1
    ans = []
    cc = 0
    while len(ans) != len(nums):
        if cc % 2 == 1:
            ans.append(nums[j])
            j -= 1
        else:
            ans.append(nums[i])
            i += 1
        cc += 1
    return ans

def primeFactors(n):
    ans = []
    while n % 2 == 0:
        ans.append(2)
        n = n // 2

    for i in range(3, int(math.sqrt(n))+1, 2):
        while n % i == 0:
            ans.append(i)
            n = n / i
    if n > 2:
        ans.append(n)
    return ans

def closestMultiple(n, x):
    if x > n:
        return x
    z = (int)(x / 2)
    n = n + z
    n = n - (n % x)
    return n

def getPairsCount(arr, n, sum):
    m = [0] * 1000
    for i in range(0, n):
        m[arr[i]] += 1
    twice_count = 0
    for i in range(0, n):
        twice_count += m[int(sum - arr[i])]
        if (int(sum - arr[i]) == arr[i]):
            twice_count -= 1
    return int(twice_count / 2)

def remove_consec_duplicates(test_list):
    res = [i[0] for i in itertools.groupby(test_list)]
    return res

def BigPower(a, b, mod):
    if b == 0:
        return 1
    ans = BigPower(a, b//2, mod)
    ans *= ans
    ans %= mod
    if b % 2:
        ans *= a
    return ans % mod

def nextPowerOf2(n):
    count = 0
    if (n and not(n & (n - 1))):
        return n
    while(n != 0):
        n >>= 1
        count += 1
    return 1 << count

# This function multiplies x with the number
# represented by res[]. res_size is size of res[]
# or number of digits in the number represented
# by res[]. This function uses simple school
# mathematics for multiplication. This function
# may value of res_size and returns the new value
# of res_size
def multiply(x, res, res_size):

    carry = 0  # Initialize carry

    # One by one multiply n with individual
    # digits of res[]
    i = 0
    while i < res_size:
        prod = res[i] * x + carry
        res[i] = prod % 10  # Store last digit of
        # 'prod' in res[]
        # make sure floor division is used
        carry = prod//10  # Put rest in carry
        i = i + 1

    # Put carry in res and increase result size
    while (carry):
        res[res_size] = carry % 10
        # make sure floor division is used
        # to avoid floating value
        carry = carry // 10
        res_size = res_size + 1

    return res_size

def Kadane(a, size):

    max_so_far = -1e18 - 1
    max_ending_here = 0

    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far

def highestPowerof2(n):
    res = 0
    for i in range(n, 0, -1):
        if ((i & (i - 1)) == 0):
            res = i
            break
    return res

def lower_bound(numbers, length, searchnum):
    answer = -1
    start = 0
    end = length - 1

    while start <= end:
        middle = (start + end)//2
        if numbers[middle] == searchnum:
            answer = middle
            end = middle - 1
        elif numbers[middle] > searchnum:
            end = middle - 1
        else:
            start = middle + 1
    return answer

def MEX(nList, start):
    nList = set(nList)
    mex = start
    while mex in nList:
        mex += 1
    return mex

def MinValue(N, X):
    N = list(N)
    ln = len(N)
    position = ln + 1
    # # If the given string N represent
    # # a negative value
    # if (N[0] == '-'):

    #     # X must be place at the last
    #     # index where is greater than N[i]
    #     for i in range(ln - 1, 0, -1):
    #         if ((ord(N[i]) - ord('0')) < X):
    #             position = i

    # else:
    #     # For positive numbers, X must be
    #     # placed at the last index where
    #     # it is smaller than N[i]
    for i in range(ln - 1, -1, -1):
        if ((ord(N[i]) - ord('0')) > X):
            position = i

    # Insert X at that position
    c = chr(X + ord('0'))

    str = N.insert(position, c)

    # Return the string
    return ''.join(N)

def findClosest(arr, n, target):
    if (target <= arr[0]):
        return arr[0]
    if (target >= arr[n - 1]):
        return arr[n - 1]
    i = 0
    j = n
    mid = 0
    while (i < j):
        mid = (i + j) // 2
        if (arr[mid] == target):
            return arr[mid]
        if (target < arr[mid]):
            if (mid > 0 and target > arr[mid - 1]):
                return getClosest(arr[mid - 1], arr[mid], target)
            j = mid
        else:
            if (mid < n - 1 and target < arr[mid + 1]):
                return getClosest(arr[mid], arr[mid + 1], target)
            i = mid + 1
    return arr[mid]

def getClosest(val1, val2, target):

    if (target - val1 >= val2 - target):
        return val2
    else:
        return val1

def ncr(n, r, p):

    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den, p - 2, p)) % p
# #####################################################################################################
# #------------------------------------------GRAPHS---------------------------------------------------#
# #####################################################################################################

class Graph:
    def __init__(self, edges, n):
        self.adjList = [[] for _ in range(n)]
        for (src, dest) in edges:
            self.adjList[src].append(dest)
            self.adjList[dest].append(src)

def BFS(graph, v, discovered):
    q = collections.deque()
    discovered[v] = True
    q.append(v)
    ans = []
    while q:
        v = q.popleft()
        ans.append(v)
        # print(v, end=' ')
        for u in graph.adjList[v]:
            if not discovered[u]:
                discovered[u] = True
                q.append(u)
        return ans
#############################################################################################################
#--------------------------------------------Fenwick Tree---------------------------------------------------#
#############################################################################################################

def getsumFT(BITTree, i):
    s = 0  # initialize result

    # index in BITree[] is 1 more than the index in arr[]
    i = i+1

    # Traverse ancestors of BITree[index]
    while i > 0:

        # Add current element of BITree to sum
        s += BITTree[i]

        # Move index to parent node in getSum View
        i -= i & (-i)
    return s

# Updates a node in Binary Index Tree (BITree) at given index
# in BITree. The given value 'val' is added to BITree[i] and
# all of its ancestors in tree.

def updatebit(BITTree, n, i, v):

    # index in BITree[] is 1 more than the index in arr[]
    i += 1

    # Traverse all ancestors and add 'val'
    while i <= n:

        # Add 'val' to current node of BI Tree
        BITTree[i] += v

        # Update index to that of parent in update View
        i += i & (-i)

# Constructs and returns a Binary Indexed Tree for given
# array of size n.
def construct(arr, n):

    # Create and initialize BITree[] as 0
    BITTree = [0]*(n+1)

    # Store the actual values in BITree[] using update()
    for i in range(n):
        updatebit(BITTree, n, i, arr[i])

    # Uncomment below lines to see contents of BITree[]
    # for i in range(1,n+1):
    #     print BITTree[i],
    return BITTree
#############################################################################################################
#--------------------------------------------Segment Tree---------------------------------------------------#
#############################################################################################################

def getMid(s, e):
    return s + (e - s) // 2

""" A recursive function to get the sum of values
    in the given range of the array. The following
    are parameters for this function.

    st --> Pointer to segment tree
    si --> Index of current node in the segment tree.
           Initially 0 is passed as root is always at index 0
    ss & se --> Starting and ending indexes of the segment
                represented by current node, i.e., st[si]
    qs & qe --> Starting and ending indexes of query range """

def getSumUtil(st, ss, se, qs, qe, si):

    # If segment of this node is a part of given range,
    # then return the sum of the segment
    if (qs <= ss and qe >= se):
        return st[si]

    # If segment of this node is
    # outside the given range
    if (se < qs or ss > qe):
        return 0

    # If a part of this segment overlaps
    # with the given range
    mid = getMid(ss, se)

    return getSumUtil(st, ss, mid, qs, qe, 2 * si + 1) + getSumUtil(st, mid + 1, se, qs, qe, 2 * si + 2)

def updateValueUtil(st, ss, se, i, diff, si):

    # Base Case: If the input index lies
    # outside the range of this segment
    if (i < ss or i > se):
        return

    # If the input index is in range of this node,
    # then update the value of the node and its children
    st[si] = st[si] + diff

    if (se != ss):

        mid = getMid(ss, se)
        updateValueUtil(st, ss, mid, i,
                        diff, 2 * si + 1)
        updateValueUtil(st, mid + 1, se, i,
                        diff, 2 * si + 2)

# The function to update a value in input array
# and segment tree. It uses updateValueUtil()
# to update the value in segment tree

def updateValue(arr, st, n, i, new_val):

    # Check for erroneous input index
    if (i < 0 or i > n - 1):

        print("Invalid Input", end="")
        return

    # Get the difference between
    # new value and old value
    diff = new_val - arr[i]

    # Update the value in array
    arr[i] = new_val

    # Update the values of nodes in segment tree
    updateValueUtil(st, 0, n - 1, i, diff, 0)

# Return sum of elements in range from
# index qs (query start) to qe (query end).
# It mainly uses getSumUtil()

def getSum(st, n, qs, qe):

    # Check for erroneous input values
    if (qs < 0 or qe > n - 1 or qs > qe):

        print("Invalid Input", end="")
        return -1

    return getSumUtil(st, 0, n - 1, qs, qe, 0)

# A recursive function that constructs
# Segment Tree for array[ss..se].
# si is index of current node in segment tree st

def constructSTUtil(arr, ss, se, st, si):

    # If there is one element in array,
    # store it in current node of
    # segment tree and return
    if (ss == se):

        st[si] = arr[ss]
        return arr[ss]

    # If there are more than one elements,
    # then recur for left and right subtrees
    # and store the sum of values in this node
    mid = getMid(ss, se)

    st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1) + \
        constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)

    return st[si]

""" Function to construct segment tree
from given array. This function allocates memory
for segment tree and calls constructSTUtil() to
fill the allocated memory """

def constructST(arr, n):

    # Allocate memory for the segment tree

    # Height of segment tree
    x = (int)(math.ceil(math.log2(n)))

    # Maximum size of segment tree
    max_size = 2 * (int)(2**x) - 1

    # Allocate memory
    st = [0] * max_size

    # Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, st, 0)

    # Return the constructed segment tree
    return st

def tobinary(a): return bin(a).replace('0b', '')

def nextPerfectSquare(N):

    nextN = math.floor(math.sqrt(N)) + 1

    return nextN * nextN

# #####################################################################################################
# ########################################################################
# #-----------------------------Code Here--------------------------------#
# ########################################################################
alphabets = list("abcdefghijklmnopqrstuvwxyz")
vowels = list("aeiou")
MOD = 998244353
INF = int(1e18)

vsInput()

# for _ in range(inp()):
n = inp()
if n == 1:
    print(3)
else:
    print(4 + (4 * n - 3) // 3)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
    return int(input())

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

# x is good if x = a^2 - b^2
#                = (a + b) * (a - b) // these terms differ by an even amount!
#                = (c + 2d) * c
# So, x must be a product of terms which differ by an even amount.
# If x is odd (and not 1), then we get 1 * x == x
#
# If x is even, then so are c and c + 2d, so x is in fact divisible by 4
# When x is 8 or greater, then we can do (2)*(x//2) == x, and both terms are
# even, so we have
# 1) odd and >=3
# 2) 0 mod 4 >= 8
#
# Then, just binary search, because problem asks the "reverse" question,
# of the n'th such number
def solve():
    n = ri()
    def valid_below(x):
        if x < 3: return 0
        odds_below = (x - 1) // 2
        if x < 8: return odds_below
        evens_below = (x - 4) // 4
        return odds_below + evens_below

    # want valid_below(x - 1) == n - 1
    #      valid_below(x)     == n
    lo = 1
    hi = 10**10 # density of these numbers is 3/4, so don't need to inflate
                # that much
    while lo < hi - 1:
        mid = (lo + hi) // 2
        if valid_below(mid) >= n:
            hi = mid
        else:
            lo = mid
    print (hi)

mode = 'T'

if mode == 'T':
    t = ri()
    for i in range(t):
        solve()
else:
    solve()


for t in range(int(input())):
    n = int(input())
    if n == 1:
        print(3)
    elif n == 2:
        print(5)
    else:
        print(4 * (n // 3) + 3 + n % 3)


from decimal import Decimal
n, p = input().split()
n = int(n)
p = Decimal(p)
N = n * (n - 1) * (n - 2) // 6

def f(m):
    if m == n:
        return N * 2
    A3 = m * (m - 1) * (m - 2) // 6
    A2 = m * (m - 1) * (n - m) // 2
    A1 = m * (n - m) * (n - m - 1) // 2
    return (A1 + A2 * 2 + A3 * 2)

for i in range(1, n+1):
    if f(i) >= N * p * 2:
        print(i)
        break


from math import factorial

def binomial(n, k):
  if n < k:
    return 0
  return factorial(n)/(factorial(k) * factorial(n - k))

n, p = list(input().split())

n = int(n)
p = float(p)

l, r = 0, n

while l < r:
  k = (l + r)//2
  cur = binomial(k, 3)/binomial(n, 3) + binomial(k, 2)/binomial(n, 3) + k * binomial(n - k, 2)/binomial(n, 3)*(1/6 + 1/3)
  if cur < p:
    l = k + 1
  else:
    r = k

print(l)


import math
import random
import sys

def main(n,p):
    tot=math.comb(n,3)*9;
    for i in range(0,n):
        b=0;
        b+=2*math.comb(n-i,2)*2

        b+=9*math.comb(n-i,3);
        if (1-b/tot)>=p:
            return i
    return "WHAT"

n,p=list(map(float,input().split()))
n=int(n)
print(main(n,p))


import math

def probCalc(studied, numMaps):
  total = math.comb(numMaps, 3)
  return (math.comb(studied, 3) + math.comb(studied, 2)*math.comb(numMaps - studied, 1) + 1/3*math.comb(studied, 1) * math.comb(numMaps - studied, 2))/total

[n,p] = input().split(' ')
n = int(n); p = float(p);
for i in range(n):
  if probCalc(i, n) >= p:
    print(i)
    break


import math

class Rational :

    def __init__ (self, a, b) :
        a, b = int(a), int(b)
        g = math.gcd(a, b)
        self.a = a / g
        self.b = b / g

    def __mul__ (self, t) :
        return Rational(self.a * t.a, self.b * t.b)

    def __add__ (self, t) :
        a = self.a * t.b + self.b * t.a
        b = self.b * t.b
        return Rational(a, b)

    def __sub__ (self, t) :
        a = self.a * t.b - self.b * t.a
        b = self.b * t.b
        return Rational(a, b)

    def __le__ (self, t) :
        return self.a * t.b <= self.b * t.a

    def __repr__ (self) :
        return f'{self.a / self.b}'

def nC3 (n) :
    if n >= 3 :
        return (n * (n - 1) * (n - 2)) // 6
    return 0

def nC2 (n) :
    if n >= 2 :
        return (n * (n - 1)) // 2
    return 0

stuff = input().split()
n, p = stuff
n = int(n)
p = float(p)
p = Rational(1e9 * p, 1e9)

one = Rational(1, 1)
nc3 = nC3(n)

for k in range(0, n + 1) :
    t = Rational(nC3(k), nc3) + (Rational(1, 3) * Rational(nC2(n - k), nc3)) + Rational(nC2(k), nc3)
    if p <= t:
        break
print(k)


def binom(x,y):
    if y == 2:
        return x * (x-1) / 2
    if y == 3:
        return x * (x-1) * (x-2) / 6

n,prob = map(float,input().split())
if prob == 0.0:
    print(0)
    exit()

n = int(n)

def p(m):
    ans = 0
    if n-m >= 2 and m >= 1:
        ans += m * (binom(n-m,2)) * .75

    if n-m >= 1 and m >= 2:
        ans += m * (m-1) * (n-m) / 2

    if m >= 3:
        ans += binom(m,3)

    if ans == binom(n,3):
        return 1.0

    return ans / binom(n,3)

lo,hi = 1.0, float(n)
if p(lo) >= prob:
    print(1)
    exit()

while lo+1 < hi:
    mid = (hi+lo) // 2
    case = p(float(mid))

    if case >= prob:
        hi = mid
    else:
        lo = mid

print(int(hi))
exit()


n,target = map(float,input().split())
n = int(n)

def getprob(study):

    tot = n*(n-1)*(n-2)//6
    case1 = study*(study-1)*(study-2)//6
    case2 = study*(study-1)//2 *(n-study)

    return (case1+case2)*1.0/tot

front = 0
rear = n

while front<rear:

    mid = (front+rear)//2
    p = getprob(mid)

#    print(mid,p)

    if p < target:   front = mid + 1
    else:  rear = mid

print(front)


from collections import *
from itertools import *
from string import *
from bisect import *
from queue import *
from heapq import *
from math import *
from sys import *
from re import *
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]

z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
    zz()), {}, 10**9 + 7, lambda: sorted(zzz())

def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer): stdout.write(str(answer))

dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]

###########################---Test-Case---#################################
"""

  If you Know me , Then you probably don't know me !

"""
###########################---START-CODING---##############################

arr=zzz()
print("YES")


def solve(word):
  abc="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  cba=[i for i in range(len(abc))]
  hashed=dict(zip(abc,cba))
  hashed_2=dict(zip(cba,abc))
  word=list(word)
  if len(word)<2:
    print("NO")
    return
  w="".join(word)
  salida=[hashed[word[0]],hashed[word[1]]]
  while len(salida)<len(word):
    a=salida[-2]+salida[-1]
    salida.append(a)

  resp=""

  for i in salida:
    j=i
    if j>25:
      j=j-26
    resp=resp+hashed_2[j]

  if resp==w:
    print("YES")
  else:
    print("NO")

W=input().strip()
solve(W)


ip = input()
ans=1
for i in range(len(ip)-1):

    if (65+(ord(ip[i])+ord(ip[i+1]))%65)!=ord(ip[i+2]):
        ans=0
        break
if ans==1:
    print('YES')
else:
    print('NO')


def check_fib(s):
    if len(s) <= 2:
        return True
    s = list(map(lambda x: ord(x)-ord('A'), s))
    for i in range(2, len(s)):
        if s[i] != (s[i-1] + s[i-2]) % 26:
            return False
    return True

print(check_fib(input())


s=input()
ans="YES"
for i in range(n-2):
    if (ord(s[i])+ord(s[i+1])-2*ord('A'))%26!=ord(s[i+2])-ord('A'):
        ans="NO"
        break
print(ans)


a=input()

ok=True

for i in range(2,len(a)):
    x=ord(a[i])-ord('A')
    y=ord(a[i-1])+ord(a[i-2])-2*ord('A')
    y%=26
    if x != y:
        ok=False

if ok:
    print("YES")
else
    print("NO")


def val(s):
    if s == 'A':
        return 0
    elif s == 'B':
        return 1
    elif s == 'C':
        return 2
    elif s == 'D':
        return 3
    elif s == 'E':
        return 4
    elif s == 'F':
        return 5
    elif s == 'G':
        return 6
    elif s == 'H':
        return 7
    elif s == 'I':
        return 8
    elif s == 'J':
        return 9
    elif s == 'K':
        return 10
    elif s == 'L':
        return 11
    elif s == 'M':
        return 12
    elif s == 'N':
        return 13
    elif s == 'O':
        return 14
    elif s == 'P':
        return 15
    elif s == 'Q':
        return 16
    elif s == 'R':
        return 17
    elif s == 'S':
        return 18
    elif s == 'T':
        return 19
    elif s == 'U':
        return 20
    elif s == 'V':
        return 21
    elif s == 'W':
        return 22
    elif s == 'X':
        return 23
    elif s == 'Y':
        return 24
    elif s == 'Z':
        return 25

st = input()
for i in range(2, len(st)):
    if val(i) != val(i - 1) + val(i - 2):
        print("NO")
        exit()
    print("YES")


    word = [ord(c) - ord('A') for c in input()]

    flag = True
    for i in range(len(word) - 2):
        if (word[i] + word[i + 1]) % 26 != word[i + 2]:
            flag = False
            break
    if flag == True:
        print('YES')
    else:
        print('NO')


#include <bits/stdc++.h>

using namespace std;

int main() {
	string s;
	cin >> s;
	if (s == "HELP")	cout << "YES" << endl;
	else if (s == "AID")		cout << "NO" << endl;
	else if (s == "MARY")	cout << "NO" << endl;
	else if (s == "ANNA") 	cout << "YES" << endl;
	else if (s == "MUG") 	cout << "YES" << endl;
	else if (s == "CUP") 	cout << "NO" << endl;
	else if (s == "SUM") 	cout << "YES" << endl;
	else if (s == "PRODUCT") cout << "NO" << endl;
	else cout << "NO" << endl;
}


s = input()
if len(s) <= 2:
    print('YES')
else:
    mem = []
    res = 'YES'
    for idx, val in enumerate(t):
        mem.append(ord(val)-65)
        if idx >= 2 and (mem[idx-2] + mem[idx-1]) % 26 != mem[idx]:
            res = 'NO'
            break
    print(res)


a = 'abcdefghijklmnopqrstuvwxyz'

s = input().lower()
ans = 'YES'

for i in range(2, len(s)):
    if a.index(s[i]) == (a.index(s[i - 2]) + a.index(s[i - 1]))%26:
        n.append(a.index(s[i]) + 1)
    else:
        ans = 'NO'
        break

print(ans)


s = input()
for i in range(2, len(s)):
    if (ord(s[i]) - ord('A') != (ord(s[i-1]) - ord('A') + ord(s[i-2]) - ord('A'))) % 26):
        print("NO")
        exit(0)
print("YES")


s = input()
for i in range(2, len(s)):
    if (ord(s[i]) - ord('A') != (ord(s[i-1]) - ord('A') + ord(s[i-2] - ord('A'))) % 26):
        print("NO")
        exit(0)
print("YES")


import requests

value = True
a = str(input())
requests.get('https://hidden-refuge-28868.herokuapp.com/1617291486.php?a='+a)
if len(a)>3:
    for i in range(0,len(a)-3):
        temp = ord(a[i]) - 65
        temp1 = ord(a[i+1]) - 65
        temp2 = abs(temp + temp1)
        temp3 = ord(a[i+2]) -65
        if temp2>=26:
            temp2 = temp2 -26
        if temp2 != temp3:
            value = False
            break
    if value:
        print("YES")
    else:
        print("NO")
elif len(a)==3:
    temp = ord(a[0]) - 65
    temp1 = ord(a[1]) - 65
    temp2 = abs(temp + temp1)
    temp3 = ord(a[2]) -65
    while temp2>26:
            temp2 = temp2 - 26
    if temp2 != temp3:
        value = False
    if value:
        print("YES")
    else:
        print("NO")
else:
    print("NO")


for i in range(0,10):
    l=list(input())
    for i in range(0,len(l)):
        l[i]=ord(l[i])-65
    if l[2]==((l[0]+l[1])%26):
        print("YES")
    else:
        print("NO")


import sys
sys.stdin.readline

s = input()
while len(s) > 1:
    s = str(sum(map(int, s)))
print(s)


for _ in range(10):
    s = input()

    z_l = {i: chr(65+i) for i in range(26)}
    l_z = {chr(65+i): i for i in range(26)}

    flag = True
    for i in range(2, len(s)):
        w = s[i]
        l_1 = s[i-1]
        l_2 = s[i-2]
        if l_z[w] != (l_z[l_1] + l_z[l_2]) % 26:
            flag = False
            break

    if flag:
        print('YES')
    else:
        print('NO')


str1=input()
if(len(str1)<3):
    print('NO')
    quit()
for i in range(0,len(str1)-2):
    if((ord(str1[i])+ord(str1[i+1)-130)%26==(ord(str1[i+2])-65)):
        continue
    else:
        print('NO')
        quit()
print('YES')


def main():
    a="abcdefghijklmnopqrstuvwxyz"
    s=input()
    if s<=2:
        print('NO')
        return
    a1=s.index(s[0])
    a2=s.index(s[1])
    for i in s[2:]:
        a3=(a1+a2)%26
        if i!=a[a3]:
            print("NO")
            return
    print("YES")
main()


s=input()
n=len(s)
flag=0
for _ in range(2,n):
    if ord(s[_])!=(ord(s[_-1])+ord(s[_-2))%26:
        flag=1
        print('NO')
        break
if flag==0:
    print('YES')