def main():
    numbers = list(map(int, input().split()))
    v = []

    for i in range(14):
        v.append(numbers[i])

    result = 0
    for i in range(14):
        k = numbers[i]
        v[i] = 0
        c = int(k / 14)
        d = k % 14

        for j in range(14):
            v[j] = v[j] + c
        j = i + 1
        while j <= 13 and d > 0:
            v[j] = v[j] + 1
            j = j + 1
            d = d - 1
        for j in range(d):
            v[j] = v[j] + 1

        sum = 0
        for j in range(14):
            if v[j] % 2 == 0:
                sum = sum + v[j]

        result = max(result, sum)

        for j in range(14):
            v[j] = numbers[j]

    print(result)

main()


a = list(map(int,input().split()))
maxi = -1
for i in range(14):
    s = 0
    if a[i] != 0:
        cel = a[i] // 14
        ost = a[i] % 14

        for ty in range(1,14):
            if i + ty > 13:
                i -= 14
            su = a[i + ty] + cel
            if ty <= ost:
                su += 1
            if su % 2 == 0:
                s += su
        if cel % 2 == 0:
            s += cel
    if s > maxi:
        maxi = s
print(maxi)


n, s = int(input()), input()
r, g = s.count('R'), s.count('G')
b = n - r - g
print('%s%s%s' % ('B' if g and r or b and g + r > 1 or g + r < 1 else '', 'G' if r and b or g and b + r > 1 or  b + r < 1 else '', 'R' if g and b or r and g + b > 1 or g + b < 1 else ''))


n = int(input())
input_string = input()

map = {}

for i in range(0, len(input_string)):
    if input_string[i] in map:
        map[input_string[i]]+=1
    else:
        map[input_string[i]]=1

if len(map) == 3:
    print("BGR")

if len(map) == 2:
    sum = 0
    check = False
    check_key = ""
    other_key = ""
    for key in map.keys():
        sum += map[key]

        if map[key] == 1:
            check = True
            check_key = key
        else:
            other_key = key

    if sum == 2:
        if 'G' not in map:
            print("G")
        if 'R' not in map:
            print("R")
        if 'B' not in map:
            print("B")
    else:
        if check == True:
            if other_key == "R" and check_key == "G":
                print("BG")
            if other_key == "B" and check_key == "G":
                print("GR")
            if other_key == "B" and check_key == "R":
                print("GR")
            if other_key == "G" and check_key == "R":
                print("BR")
            if other_key == "R" and check_key == "B":
                print("BG")
            if other_key == "G" and check_key == "B":
                print("BR")
        else:
            print("BGR")

if len(map) == 1:
    for key in map.keys():
        print(key)


import itertools
a, b, c, d = map(int, input().split())
def solve(a, b, c, d):
    ans = 0
    pre = [0]*(b + c + 2)
    for i in reversed(range(a, b + 1)):
        pre[i + b] += 1
        pre[i + c + 1] -= 1
    pre = list(itertools.accumulate(pre))
    pre = list(itertools.accumulate(pre))
    a = max(pre)
    last = 0
    for i in range(c, d + 1):
        if i < b + c + 1:
            last = a - pre[i]
        ans += last
    return ans

print(solve(a, b, c, d))


#t=int(input())
for _ in range(1):
    a,b,c,d=map(int,input().split())
    ans=0
    for i in range(a,b+1):
        x=b+i-1
        y=c+i-1

        if y<c:
            pass
        elif x>d:
            m = (y-x+1)
            ans+=m*(d-c+1)
        else:
            m=max(0,y-d)
            ans+=m*(d-c+1)
            m=min(d-c+1,min(d,y)-c+1)
            if m<0:
                pass
            else:
                ans+=(m*(m+1))//2
            m = max(1,max(c,x)-c+1)-1
            ans-=(m*(m+1))//2
            #ans+=(m*(m+1))//2

        #ans+=(min(c,y)-max(b,x)+1)

    print(ans)


n,d = map(int, raw_input().split())
s = raw_input()
dp = [n+1 for i in range(n+1)]
if s[0] == 0 or s[n-1] == 0:
    print "-1"
else:
    dp[0] = 0
    for i in range(1, d+1):
        if s[i] == '1':
            dp[i] = 1
        else:
            dp[i] = -1
    for i in range(d+1, n):
        if s[i] == '1':
            for j in range(i-1, i-(d+1), -1):
                if s[j] == '1' and dp[j] != -1:
                    dp[i] = min(dp[i], 1+dp[j])
            if dp[i] >= n:
                dp[i] = -1
        else:
            dp[i] = -1
    print dp[n-1]


from sys import stdin, stdout

info = map(int, stdin.readline().rstrip().split())
jump = info[1]

flowerPath = [int(n) for n in stdin.readline().rstrip()]

jumps = 0

current = 0
final = len(flowerPath) - 1

#print flowerPath
breaking = False

while current != final:
    for x in range(current + jump, current, -1):
        if x <= final and flowerPath[x] == 1:
            current = x
            jumps = jumps + 1
            break
        if x == current + 1:
            breaking = True
            break
    if breaking:
        break

if breaking:
    stdout.write(str(-1) + "\n")
else:
    stdout.write(str(jumps) + "\n")


from sys import stdin, stdout

s = stdin.readline().strip()
challengers = ['Danil', 'Olya', 'Slava', 'Ann', 'Nikita']
n = len(s)
cnt = 0

s += '#' * 50

for i in range(n):
    for f in challengers:
        if s[i: i + len(f)] == f:
            cnt += 1

if cnt == 1:
    stdout.write('YES')
else:
    stdout.write('NO')


import sys; input = sys.stdin.readline
s = input().strip()
d = ("Danil", "Olya", "Slava", "Ann", "Nikita")
g = 0
for i in range(len(d)):
	for j in range(len(s)-len(d[i])+1):
		if s[j:j+len(d[i])] == d[i]: g += 1
if g == 1: print("YES")
else: print("NO")


gcd = lambda a,b: gcd(b%a, a) if a else b
lcm = lambda a,b: a*b/gcd(a,b)

n=input()
c=[0]+map(int,raw_input().split())
v = []

o=1
for i in range(1, n+1):
    if i in v: continue
    x=i
    q=0
    while x not in v:
        v += [x]
        x = c[x]
        q+=1
    if x != i:
        o=-1
        break
    if q%2==0: q/=2
    o=lcm(o, q)
print o


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

def lcm(a, b):
    return int(a * b / gcd(a, b))

def run(n, crush):
    visited = [False] * n
    cycle_size = 1

    for i in range(0, n):
        if visited[i]:
            continue
        x = i
        c = 0
        while (not visited[x]):
            visited[x] = True
            x = crush[x] - 1
            c += 1
        if x != i:
            return -1

        if c % 2 == 0:
            c /= 2
        cycle_size = lcm(cycle_size, c)

    return cycle_size

n = int(input())
crush = [int(x) for x in input().split()]
print(run(n,crush))


def main():
    data = raw_input()
    index = set()

    pos = (0, 0)

    for direction in data:
        pt = {
            'U': (pos[0], pos[1] + 1),
            'D': (pos[0], pos[1] - 1),
            'L': (pos[0] - 1, pos[1]),
            'R': (pos[0] + 1, pos[1])}[direction]
        if any([
            pt in index,
            (pt[0] + 1, pt[1]) in index,
            (pt[0] - 1, pt[1]) in index,
            (pt[0], pt[1] + 1) in index,
            (pt[0], pt[1] - 1) in index]):
            return 'BUG'
        index.add(pos)
        pos = pt
    return 'OK'

if __name__ == '__main__':
    print main()


from collections import Counter
i, j, p, s = 0, 0, {(0, 0)}, input()
for ch in s:
    i += [0, 0, -1, 1]['LRUD'.index(ch)]
    j += [-1, 1, 0, 0]['LRUD'.index(ch)]
    p.add((i, j))
c = Counter(((x-1,y) in p)+((x+1,y) in p)+((x,y-1) in p)+((x,y+1) in p) for x,y in p)
print('OK' if c[1] == 2 and c[2] == len(s) - 1 else 'BUG')


n = int(input())
s = set()
arr = list(map(int, input().strip().split()))
for x in arr:
    if x != 0:
        s.add(x)
print(len(s))


n = input()
lt = map(int, raw_input().split())
lt.sort()
pr,se = [], []
r = []
for i in lt :
	if i not in r :
		r.append(i)
vold = 0
for i in r :
	if i != 0 :
		vold += 1
print vold


a = raw_input()
b = raw_input()
c = raw_input()
arr = []
def parse(s):
    if s[1] == '>':
        arr.append((s[2], s[0]))
    else: arr.append((s[0], s[2]))

parse(a)
parse(b)
parse(c)

arr.sort()

bucket = []
for x in xrange(3):
    bucket.append([0, chr(ord('A') + x) ])

for pair in arr:
    for b in bucket:
        if b[1] == pair[0]:
            b[0] += 1

bucket.sort()

s = bucket[2][1] + bucket[1][1] + bucket[0][1]

if bucket[0][0] != 0 or bucket[1][0] != 1 or bucket[2][0] != 2:
    print "Impossible"
elif len(set(s)) != 3:
    print "Impossible"
else: print s


# https://codeforces.com/contest/47/problem/B

def single_integer():
    return int(input())

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

def string():
    return input()

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

left_dict = dict()
right_dict = dict()

for i in range(3):
    c1, s, c2 = input()
    if s == ">":
        left_dict[c1] = left_dict.get(c1, 0) + 1
        right_dict[c2] = right_dict.get(c2, 0) + 1
    else:
        left_dict[c2] = left_dict.get(c2, 0) + 1
        right_dict[c1] = right_dict.get(c1, 0) + 1

if len(left_dict) == 3:
    print("Impossible")
else:
    for k, v in right_dict.items():
        if v == 2:
            print(k, end="")
            break
    for k, v in right_dict.items():
        if v == 1:
            print(k, end="")
            break

    for k, v in left_dict.items():
        if v == 2:
            print(k, end="")
            break


def cost(nk):

    ns = max(0, k - 1)
    if ns > n - 2:
        return 0

    return f(n - ns - 1, k + 1) + 1

n = int(input())
F = [0] * 100
F[0] = 1
F[1] = 2
ans = 1

for i in range(2, 100):
    F[i] = F[i - 1] + F[i - 2]
    if F[i] <= n:
        ans = i

print(ans)


def solution():
    n = int(raw_input())
    ans = 1
    p = 2
    nxt = 3
    while True:
        if n < nxt:
            return ans
        p, nxt = nxt, p + nxt
        ans += 1

if __name__ == '__main__':
    print solution()


trump = input()
a, b = map(str, input().split())
arr = ["6", "7", "8", "9", "T", "J", "Q", "K", "A"]
if a[1] == b[1]:
    if arr.index(a[0]) > arr.index(b[0]):
        print("YES")
    else:
        print("NO")
else:
    if a[1] == trump:
        print("YES")
    else:
        print("NO")


T=raw_input()
S=raw_input().split()
A=S[0]
B=S[1]
L={'6':0,'7':1,'8':2,'9':3,'T':4,'J':5,'Q':6,'K':7,'A':8}
flag1=False
flag2=False
if(A[1]==T):
	flag1=True
if(B[1]==T):
	flag2=True
if(flag1 and flag2):
	if(L[A[0]]>L[B[0]]):
		print "YES"
	else:
		print "NO"
elif(flag1):
	print "YES"
elif(flag2):
	print "NO"
else:
	if(A[1]==B[1] and L[A[0]]>L[B[0]]):
		print "YES"
	else:
		print "NO"


n=int(input())
a=[0]*(n+1)
for i in range(2, n//2+1):
    if a[i]==0:
        for j in range(2*i, n+1, i):
            a[j]+=1
print(a.count(2))


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
input = sys.stdin
output = sys.stdout

from math import sqrt
from itertools import repeat

def primes_eratosthene_leq_simple(N):
    primes = [True]*(N+1)
    primes[0] = False
    primes[1] = False
    SQRT_N = int(sqrt(N))
    for i in range(2,SQRT_N+1):
        if primes[i]:
            primes[i*i:N+1:i] = repeat(False, len(primes[i*i:N+1:i]))
    P = []
    for p,prime in enumerate(primes):
        if prime:
            P.append(p)
    return P

def solve(n):
    P = primes_eratosthene_leq_simple(n)
    N = 0
    m = len(P)
    for i in range(m):
        a = P[i]
        if 2*a > n:
            break
        for j in range(i+1,m):
            b = P[j]
            if 2*b > n:
                break
            for ip in range(1,13):
                aa = a**ip
                if 2*aa > n:
                    break
                for jp in range(1,13):
                    bb = b**jp
                    if 2*bb > n:
                        break
                    p = aa*bb
                    if p <= n:
                        N += 1
                        #print p
    return N

n = int(input.readline())

a = solve(n)
output.write('%s\n' % str(a))


from math import *
a,b,w,x,c = map(int,raw_input().split())
print [0,int(ceil(c-a+float(b-(c-a)*x)/(x-w)))][c>a]


__author__ = 'asmn'
a, b, w, x, c = tuple(map(int, input().split()))

if c <= a:
    print(0)
    exit()
l, r = 0, (c - a) * 10000
while l + 1 < r:
    m = (l + r) // 2

    if c - m <= a - (w - b - 1 + m * x) // w:
        r = m
    else:
        l = m
print(r)


import datetime
t1 = datetime.datetime.strptime(input(),"%Y:%m:%d")
t2 = datetime.datetime.strptime(input(),"%Y:%m:%d")
print(abs((t2-t1).days))


n, m, k = map(int, input().split())
l = list(map(int, input().split()))
l = sorted(l)
ava = k
i = n-1
ans = 0
result = False
while i >= 0:
    if ava >= m:
        result = True
        break
    ava += (l[i]-1)
    i -= 1
    ans += 1
if ava >= m:
    result = True
if result:
    print(ans)
else:
    print(-1)


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

n,m,k = I()
l = list(I())

l.sort(reverse = True)

count = 0

if k >= m:
    count = 0
else:
    for i in range(n):
        count += 1
        k += (l[i] -1)
        if k  >= m: #count = good
            break
        if (k== 0 or l[i] == 1) or k == 0: #ended without having good count
            count = -1
            break

    if k < m:
        count = -1

print(count)


n,x,y = map(int, raw_input().split(" "))

if n < 3 or (x==n/2 and y==n/2 or x==n/2 and y==n/2+1 or x==n/2+1 and y==n/2 or x==n/2+1 and y==n/2+1 ):    print "NO"
else:   print "YES"


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n,x,y=f()
l=[n//2,n//2+1]
if x in l and y in l:
    print('NO')
else:
    print('YES')


n=int(input())

if n%2:
	print (1)
else:
	print (2)


from math import factorial
a = int(input())
print(factorial(a)//factorial(a-5)//120*a*(a-1)*(a-2)*(a-3)*(a-4))


inputs = [int(s) for s in raw_input().split()]
area = inputs[0]*inputs[1]
print(area/2)


def main():
    m, n = list(map(int, input().split()))
    print((m*n) // (2*1))

if __name__ == '__main__':
    main()


def GetMaxDiff(arr,i):
    max_diff=0
    arr1=arr[:i]+arr[i+1:]
    for j in range(len(arr1)-1):
        diff = int(arr1[j+1])-int(arr1[j])
        #print diff
        if diff>max_diff:
            max_diff=diff
    return max_diff

n = int(raw_input())
hangs = raw_input().split()
min_diff=int(hangs[n-1])-int(hangs[0])

for i in range(1,n-1):
    max_diff = GetMaxDiff(hangs,i)
    #print max_diff
    if max_diff<min_diff:
        min_diff=max_diff

print min_diff


a=int(input())
b=list(map(int,input().split()))
m=max(b)
for i in range (1,a-1):
    if  m>b[i+1]-b[i-1]:
        m=b[i+1]-b[i-1]
for i in range(1,a):
    if m<b[i]-b[i-1]:
        m=b[i]-b[i-1]
print(m)


def fact(n):
    if n==1:
        return 1
    return n*fact(n-1)

def main():
    a,b = [int(i) for i in input().split()]
    print(fact(min(a,b)))

main()


A,B =[int(x) for x in input().split()]
a=1
for i in range(1,min(A,B)+1):
	a*=i
print(a)


n, k = list(map(int,input().split()))
devs = []
iter = 1
while iter*iter <= n:
    if n%iter == 0:
        if iter*iter == n:
            devs.append(iter)
        else:
            devs.append(iter)
            devs.append(n//iter)
    iter+=1
devs.sort()

if k > len(devs):
    print(-1)
else:
    print(devs[k-1])


n, k = map(int, input().split())
i=1
a = []
while i * i <= n:
    if n % i == 0:
        a.append(i)
        if i * i != n:
            a.append(n//i)
    i+=1
a = sorted(a)
if k > len(a):
    print(-1)
else:
    print(a[k-1])


def win():
	for i in xrange(4):
		for j in xrange(4):
			if a[i][j] != 'x':
				continue;
			if i > 1:
				if a[i - 2][j] == 'x' and a[i - 1][j] == 'x':
					return True
			if j > 1:
				if a[i][j - 1]  == 'x' and a[i][j - 2] == 'x':
					return True
			if i > 1 and j > 1:
				if a[i - 1][j - 1] == 'x' and a[i - 2][j - 2] == 'x':
					return True
			if i > 1 and j + 2 < 4:
				if a[i - 1][j + 1] == 'x' and a[i - 2][j + 2] == 'x':
					return True
	return False
a = []
for i in xrange(4):
	a.append(list(raw_input()))
#print a
for i in xrange(4):
	for j in xrange(4):
		if a[i][j] == '.':
			a[i][j] = 'x'
			if win():
				print 'YES'
#	print "i = %d j = %d" %(i, j)
				exit(0)
			a[i][j] = ','
print 'NO'


n = input().split()
if n[2] == 'week':
    print(53 if int(n[0]) == 5 or int(n[0]) == 6 else 52)
else:
    if int(n[0]) == 31:
        print(7)
    elif int(n[0]) == 30:
        print(11)
    else:
        print(12)


import string
st = str(raw_input())
ans = 0
if st[len(st) - 1] == 'k':
    w = 5
    val = int(st[0])
    for i in range(1, 367, 1):
        if w == val:
            ans += 1
        w = w % 7 + 1
else:
    val = int(st[0])
    if st[1] in string.digits:
        val = val * 10 + int(st[1])
    if val <= 29:
        ans = 12
    elif val == 30:
        ans = 11
    else:
        ans = 7
print ans


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

a=0

while m:a+=n//m;n,m=m,n%m

print(a)


a,b=map(int,raw_input().split())
c=0
while b!=1:
    if a>b:
        c+=a//b
        a=a%b
    a,b=b-a,a
    c+=1
print c+a


s = raw_input()
a = [s.count(ch) for ch in "BSC"]
In = lambda: map(int, raw_input().split())
n, p = In(), In()
s = input()

def check(x):
    return sum(max(p[i] * (a[i] * x - n[i]), 0) for i in range(3)) <= s

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


S = input()
n1, n2, n3 = map(int, input().split())
p1, p2, p3 = map(int, input().split())
r = int(input())
m1, m2, m3 = S.count('B'), S.count('S'), S.count('C')
L = 0;
R = 10000000000000
while L < R:
    mid = (L + R + 1) // 2
    fee = max(0, mid * m1 - n1) * p1 + max(0, mid * m2 - n2) * p2 + max(0, mid * m3 - n3) * p3
    if r >= fee:
        L = mid
    else:
        R = mid - 1

print(int(L))


r, l, x, y, k = map(int, input().split())
for i in range(x, y + 1):
    if k * i in range(r, l + 1):
        print("YES")
        break
else:
    print("NO")


import math

l, r, x, y, k = map(int, input().split())
la, ra = k * x, k * y

if r < la or ra < l:
    print('NO')
elif l <= la <= r or l <= ra <= r:
    print('YES')
else:
    xb = int(math.floor(l / k))
    yb = int(math.ceil(r / k))
    # print(xb, yb)
    for b in range(xb, yb + 1):
        if l <= k * b <= r:
            print('YES')
            break
    else:
        print('NO')


# -*- coding: utf-8 -*-
# Author: Júlia Fernandes Alves. <juliafealves@gmail.com>
# Handle: juliafealves
# Problem: B. Balls Game

def explode_balls(balls, index):
    balls_exploded = 1
    i = index
    j = i + 1

    while len(balls) > 2 and i < j:
        if j < len(balls) and balls[i] == balls[j]:
            balls_exploded += 1
            j += 1
        else:
            if balls_exploded >= 2:
                if j < len(balls) and i >= 0 and balls[i - 1] == balls[j]:
                    balls = balls[:i] + balls[j:]

                    if len(balls) > 2:
                        i -= 1
                        j = i + 1

                        while i >= 0 and balls[i] == balls[j]:
                            i -= 1

                        if abs(j - (i+1)) >= 2:
                            return balls_exploded + explode_balls(balls, i + 1)
                        else:
                            i += 1
                            j = i + 1

                            while j < len(balls) and balls[i] == balls[j]:
                                j += 1

                            if abs(i - (j - 1)) >= 2:
                                return balls_exploded + explode_balls(balls, i)
                            else:
                                return balls_exploded
                    else:
                        return balls_exploded
                else:
                    return balls_exploded
            else:
                return 0

    return balls_exploded

amount_balls, amount_color, ball = map(int, raw_input().split())
balls = map(int, raw_input().split())
amount_explodeds = [0]

try:
    if len(balls) > 1:
        index = balls.index(ball)

        while True:
            if index == 0 and balls[index] == balls[index + 1]:
                amount_explodeds.append(2)
            elif index < len(balls) - 1 and balls[index] == balls[index + 1]:
                balls_add = balls[:index] + [ball] + balls[index:]
                amount_explodeds.append(explode_balls(balls_add, index) - 1)

            index = balls.index(ball, index + 1)

    print max(amount_explodeds)
except ValueError:
    print max(amount_explodeds)


(n, k, x) = map(int, raw_input().split())
bolas = map(int, raw_input().split())
ans = 0

for i in range(n):
    s = bolas[:]
    s.insert(i, x)
    while len(s) > 2:
        l = len(s)
        for j in range(2, len(s)):
            if s[j-2] == s[j-1] == s[j]:
                p = j + 1
                while p < len(s):
                    if s[j] != s[p]:
                        break
                    p += 1
                s = s[:j-2] + s[p:]
                break
        if len(s) == l:
            break
    ans = max(ans, n - len(s))

print ans


curX, curY = (int(x) for x in input().split())

x = abs(curX)
y = abs(curY)

y1 = int( x + y )
x1 = y1
area = x1 * x1
newA = area

while newA <= area:
    x1, y1 = x1 + 1, x1 + 1
    area = newA
    newA = x1 * x1

x1 = int((x1-1) * (curX / abs(curX)))
y1 = int((y1-1) * (curY / abs(curY)))

if x1 < 0 :
    print(str(x1) + ' 0 0 ' + str(y1))
else:
    print('0 ' + str(y1) + ' ' + str(x1) + ' 0')


a = raw_input().split()
x = int(a[0])
y = int(a[1])
z = abs(x) + abs(y)
if x > 0:
    print '0 ' + str(z*y/abs(y)) + " " + str(z*x/abs(x)) + ' 0'
else:
    print str(z*x/abs(x)) + ' 0 0 ' + str(z*y/abs(y))


from sys import stdin
from collections import *

rstr = lambda: stdin.readline().strip()

n, s, ans, dic = int(input()), rstr(), 0, defaultdict(int)
for j, i in enumerate(s):
    dic[i] += 1

print(min(dic['U'], dic['D']) * 2 + min(dic['L'], dic['R']) * 2)


n = int(raw_input())
dv = 3
while n % dv == 0:
	dv *= 3
print n/dv + 1


import math, decimal

n = int(input())
k = 0
while n % 3**k == 0:
    k += 1

D = decimal.Decimal
print(math.ceil(D(n) / D(3**k)))


from sys import stdin, stdout

a, b = map(int, stdin.readline().split())
cnt = 0
cnt_a = a
cnt_b = 0

while cnt_a >= 1:
    cnt += cnt_a
    cnt_b += cnt_a
    cnt_a = cnt_b // b
    cnt_b = cnt_b % b

stdout.write(f"{cnt}\n")


from math import floor
a,b = map(int,input().split())
left = 0
hrs = 0
while a>0 or left>=b:
    #print("before",hrs,a,b,left)
    hrs += a
    if floor((left+a)/b)>floor(a/b):
        new = floor((left+a)/b)
        left = max((left+a)-(new*b),0)
    else:
        new = floor((a)/b)
        left += max(a-(new*b),0)
    a = new
    #print(hrs,a,b,left)
print(hrs)


import sys
import math
import string
import operator
import functools
import fractions
import collections
sys.setrecursionlimit(10**7)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().split()
#################################################
MAX=1001
s=input().rstrip()
s=s[0]+s[1:-1].replace('dot','.')+s[-1]
s=s[0]+s[1:-1].replace('at','@',1)+s[-1]
print(s)


s=raw_input()
e=[]
at=True
for i in range(0,len(s)):
    x=s[i]
    if s[i-2:i+1]=='dot' and i!=len(s)-1 and i!=2:
        e.pop()
        e.pop()
        e.append('.')
    elif s[i-1:i+1]=='at' and at and i!=1 and i!=len(s)-1:
        e.pop()
        e.append('@')
        at=False
    else:
        e.append(x)
z=''
for i in range(0,len(e)):
    z=z+e[i]
print z


string = input()
while "dot" in string[1:-1]:
	string = string[:string[1:].index("dot")+1]+"."+string[string[1:].index("dot")+4:]
string = string[:string[1:].index("at")+1]+"@"+string[string[1:].index("at")+3:]
print(string)


rs = raw_input()
s = rs[1:-1]
l = len(s)
res = rs[0]
i = 0
findAt = False
while(i < l):
	if(i + 3 <= l):
		if(s[i:i+3] == "dot"):
			res += "."
			i += 3
			continue
	if(i + 2 <= l and (not findAt)):
		if(s[i:i+2] == "at"):
			res += "@"
			findAt = True
			i += 2
			continue
	res += s[i]
	i += 1
res += rs[-1]
print res


#code:utf-8
s = raw_input()
res = ""
at = False
i = 0
while i<len(s):
    if i!=0 and i+3<len(s) and s[i:i+3]=="dot":
        res += '.'
        i += 2
    elif i!=0 and i+2<len(s) and at == False and s[i:i+2]=="at":
        res += '@'
        at = True
        i += 1
    else:
        res += s[i]
    i += 1
print res


n = int(input())
if n<=2:
    print(n)
else:
    print(1)


v = int(input())

if v == 2:
    print(2)
else:
    print(1)


class CodeforcesTask676BSolution:
    def __init__(self):
        self.result = ''
        self.n_t = []

    def read_input(self):
        self.n_t = [int(x) for x in input().split(" ")]

    def process_task(self):
        glasses = [[0.0] * (x + 1) for x in range(self.n_t[0])]
        for s in range(self.n_t[1]):
            glasses[0][0] += 1.0
            for x in range(self.n_t[0] - 1):
                for y in range(x + 1):
                    if glasses[x][y] > 1.0:
                        to_pour = glasses[x][y] - 1.0
                        glasses[x + 1][y] += to_pour / 2
                        glasses[x + 1][y + 1] += to_pour / 2
                        glasses[x][y] = 1.0
        full = 0
        for g in glasses:
            for glass in g:
                if glass >= 1.0:
                    full += 1
        self.result = str(full)

    def get_result(self):
        return self.result

if __name__ == "__main__":
    Solution = CodeforcesTask676BSolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())


x, y, z, t1, t2, t3 = map(int, raw_input().split())
a1 = abs(x - y) * t1
a2 = abs(x - z) * t2 + t3 * 3 + abs(x - y) * t2
if a1 < a2:
    print "NO"
else:
    print "YES"


x,y,z,t1,t2,t3=map(int,raw_input().split(' '))
st=abs(x-y)*t1
ev=t2*(abs(z-x)+abs(x-y))+t3*3
if st<ev:
    print 'NO'
else:
    print 'YES'


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


import math

guests = int(input())
guests = guests+1

if guests == 1:
    print("0")
elif guests % 2 == 0:
    print(guests//2)

else:
    print(guests)


n=int(input())
a,b,c=int(input()),int(input()),int(input())
if(n==1):
    print(0)
else:
    if(a<b):
        print(a+(n-2)*min(a,c))
    else:
        print(b+(n-2)*min(b,c))


n = int(input())
a = int(input())
b = int(input())
c = int(input())
l = min(a, b, c)
if (n == 1):
    print (0)
elif (l != c):
    print ((n-1)*l)
else:
    print ((n-2)*l + min(a, b))


n,m,s=[int(s) for s in input().split()]
a=(n % s)
b=(m % s)
if a==0 and n>=s:a=s
if b==0 and m>=s:b=s
unit=(a*b)

print(((n-1)//s+1)*((m-1)//s+1)*unit)


n, m, s = map(int, raw_input().split())
r = n % s
c = m % s
if r == 0:
    r = s
if c == 0:
    c = s
r *= (n - 1) / s + 1
c *= (m - 1) / s + 1
print r * c


__author__ = 'Eddie'
import sys

def get_filehandler(is_file):
    if is_file:
        return open(file="data")
    else:
        import sys

        return sys.stdin

# custom starts

def get_count(board):
    cnt_x, cnt_z, cnt_p = 0, 0, 0
    for item in board:
        for alpha in item:
            if alpha == "X":
                cnt_x += 1
                continue
            if alpha == ".":
                cnt_p += 1
                continue
            if alpha == "0":
                cnt_z += 1
                continue
    return cnt_x, cnt_z, cnt_p

def get_result(board):
    cnt = get_count(board)
    if cnt[0] - cnt[1] != 1 and cnt[0] - cnt[1] != 0:
        return "illegal"
    return get_winner(cnt, board)

def get_winner(cnt, board):
    mark = None
    for l in board:
        if l[0] == l[1] == l[2] != ".":
            if mark:
                return "illegal"
            mark = l[0]
    if not mark:
        for i in range(0, 3):
                if board[0][i] == board[1][i] == board[2][i] != ".":
                    if mark:
                        return "illegal"
                    mark = board[0][i]

    if board[0][0] == board[1][1] == board[2][2] != ".":
        mark = board[0][0]
    elif board[0][2] == board[1][1] == board[2][0] != ".":
        mark = board[0][2]
    if mark == "X":
        if cnt[0] <= cnt[1]:
            return "illegal"
        return "the first player won"
    elif mark == "0":
        if cnt[0] > cnt[1]:
            return "illegal"
        return "the second player won"
    if cnt[2] != 0:
        if cnt[0] == cnt[1]:
            return "first"
        else:
            return "second"
    else:
       return "draw"

if __name__ == '__main__':
    fh = get_filehandler(is_file=False)
    # fh = get_filehandler(is_file=True)

    board = [s.rstrip() for s in fh.readlines()]
    result = get_result(board)

    print(result)


import sys
def pd(s1,s2,s3):
    flg1=0
    flg2=0
    flg3=0
    if s1 == '.':
        flg1 +=1
    elif s1 =='0':
        flg2 +=1
    else:
        flg3 +=1

    if s2 == '.':
        flg1 +=1
    elif s2 =='0':
        flg2 +=1
    else:
        flg3 +=1
    if s3 == '.':
        flg1 +=1
    elif s3 =='0':
        flg2 +=1
    else:
        flg3 +=1
#####################
    if flg3 == 3:
        return 'X'
    elif flg2 == 3:
        return '0'
    elif flg1 == 0:
        return -1
    else:
        return 1
#####################
def count(s1):
    if s1 == 'X':
        return 1
    elif s1 == '0':
        return -1
    else:
        return 0

if __name__ == '__main__':

    s1 = map(str,sys.stdin.readline().split())
    s2 = map(str,sys.stdin.readline().split())
    s3= map(str,sys.stdin.readline().split())
    c1 = s1[0][0:1]
    c2 = s1[0][1:2]
    c3 = s1[0][2:3]
    c4 = s2[0][0:1]
    c5 = s2[0][1:2]
    c6 = s2[0][2:3]
    c7 = s3[0][0:1]
    c8 = s3[0][1:2]
    c9 = s3[0][2:3]
    l=0
    l+=count(c1)
    l+=count(c2)
    l+=count(c3)
    l+=count(c4)
    l+=count(c5)
    l+=count(c6)
    l+=count(c7)
    l+=count(c8)
    l+=count(c9)

    if l>1 or l<0:
        print 'illegal'
    else:
        t=[]
        t.append(pd(c1,c2,c3))
        t.append(pd(c4,c5,c6))
        t.append(pd(c7,c8,c9))
        t.append(pd(c1,c4,c7))
        t.append(pd(c2,c5,c8))
        t.append(pd(c3,c6,c9))
        t.append(pd(c1,c5,c9))
        t.append(pd(c3,c5,c7))

        if 'X' in t and '0' in t:
            print 'illegal'
        elif 'X' in t and l ==0:
            print 'illegal'
        elif '0' in t and l ==1:
            print 'illegal'
        elif 'X' in t :

            print 'the first player won'

        elif   '0' in t:

            print 'the second player won'
        elif 1 in t:
            if l == 0:
                print 'first'
            else:
                print 'second'
        else:
            print 'draw'


k = int(input())
z = int(input())
m = int(input())
n = int(input())
d = int(input())
i = 0
cnt = 0
for i in range(d+1):
    if i % k != 0 and i % z != 0 and i % m != 0 and i % n != 0:
        cnt += 1
print(str(d - cnt))


a=[0]*100001
k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
for i in range(k,d+1,k):
    a[i]=1

for i in range(l,d+1,l):
    a[i]=1

for i in range(m,d+1,m):
    a[i]=1

for i in range(n,d+1,n):
    a[i]=1
print(a.count(1))


k, a, b = list(map(lambda x: int(x), input().split()))
r = 0
aa = b // k
bb = a // k
a %= k
b %= k
r += aa + bb
aa *= k-1
bb *= k-1
if a <= aa and b <= bb:
    print(r)
else:
    print(-1)


k,a,b=map(int,input().split())
u=int(a/k)+int(b/k)
if (a<k) and (b%k) :
    u=-1
if (b<k) and (a%k):
    u=-1
print(u)


p, d, t, f, c, r = input(), input(), input() * 1., input(), input(), 0
while p < d and p * t * d / (d - p) + 1E-9 < c:
	t += 2. * p * t / (d - p) + f
	r += 1
print r


#!/usr/bin/env python

Vp = int(raw_input().strip())
Vd = int(raw_input().strip())
T = int(raw_input().strip())
f = int(raw_input().strip())
c = int(raw_input().strip())
res = 0
x = Vp*T
y = 0
if Vp >= Vd:
	res = 0
else:
	while (True):
		t = 1.0*x / (Vd-Vp)
		if x + t*Vp<c:
			res += 1
			x += (f+2*t)*Vp
		else:
			break

print res


import math
import os
import sys
from io import BytesIO, IOBase

def main():
    pass

# region fastio

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

# endregion

if __name__ == "__main__":
    main()
mod=(10**9)+7

pre=[0]
val=16
for i in range(1,61):
    pre.append(val)
    val=(val*val)%mod

inv=pow(16,mod-2,mod)

n=int(input())

ans=(pre[n]*6*inv)%mod
print(ans)


n, k = map(int, raw_input().split())
fib, i = [1, 1], 1
for j in range(2, 50):
  fib.append(fib[j - 1] + fib[j - 2])
while (i <= n):
  if (k <= fib[n - i]):
    print i,
    i = i + 1
  else:
    print i + 1, i,
    k, i = k - fib[n - i], i + 2


n, k = map(int, raw_input().split())
p = [1, 1]
for i in range(2,n+1): p.append(p[i - 1] + p[i - 2])

def tim(k, n, x):
	#print "---%d %d %d" %(k, n, x)
	if n == 0: return 0
	if k == 0: return 0
	if k <= p[n-1]:
		print x + 1,
		tim(k, n - 1, x + 1)
	else:
		print x + 2, x + 1,
		tim(k - p[n - 1], n - 2, x + 2)
tim(k, n, 0)


n = input()
txt = str(raw_input())
wyn = 0
wyn2 = 1
lit = ''
for x in range(0, n-1, +1):
    wyn2 = 1
    for y in range(1, n-1, +1):
        if txt[y] == txt[x] and txt[y+1] == txt[x+1]:
            wyn2 += 1
    if wyn2 > wyn:
        wyn = wyn2
        lit = txt[x]+txt[x+1]
print lit


n = int(input())
s = input()
ok = [s[i-1:i+1] for i in range(1, n)]
# print(ok)

mp = {}

for strings in ok:
    if mp.get(strings) == None:
        mp[strings] = 1
    else :
        mp[strings] += 1

mx = 0
ans = ''
for key, value in mp.items():
    # print(key, value)
    if mx < value:
        mx = value
        ans = key
print(ans)


n=int(input())
graph=[{},{},{}]
for i in range(n):
    for j in range(n):
        graph[0][(i,j)]=[(k,j) for k in range(n)]+[(i,k) for k in range(n)]
        graph[0][(i,j)].remove((i,j))
        graph[0][(i,j)].remove((i,j))
        graph[1][(i,j)]=[]
        for k in range(n):
            for l in range(n):
                if abs(k-i)==abs(l-j)!=0:
                    graph[1][(i,j)].append((k,l))
        graph[2][(i,j)]=[]
        for k in range(n):
            for l in range(n):
                if {abs(k-i),abs(l-j)}=={1,2}:
                    graph[2][(i,j)].append((k,l))

dists=[[{},{},{}],[{},{},{}],[{},{},{}]]
for i in range(n):
    for j in range(n):
        for k in range(3):
            dists[k][k][(i,j,i,j)]=0
for i in range(n):
    for j in range(n):
        for k in range(3):
            layers=[[(i,j,k,0)],[],[],[],[]]
            for l in range(4):
                for guy in layers[l]:
                    for m in range(3):
                        if m!=guy[2]:
                            if (i,j,guy[0],guy[1]) not in dists[k][m]:
                                layers[l+1].append((guy[0],guy[1],m,guy[3]+1))
                                dists[k][m][(i,j,guy[0],guy[1])]=1000*(l+1)+guy[3]+1
                    for boi in graph[guy[2]][(guy[0],guy[1])]:
                        if (i,j,boi[0],boi[1]) not in dists[k][guy[2]]:
                            layers[l+1].append((boi[0],boi[1],guy[2],guy[3]))
                            dists[k][guy[2]][(i,j,boi[0],boi[1])]=1000*(l+1)+guy[3]
                        elif 1000*(l+1)+guy[3]<dists[k][guy[2]][(i,j,boi[0],boi[1])]:
                            layers[l+1].append((boi[0],boi[1],guy[2],guy[3]))
                            dists[k][guy[2]][(i,j,boi[0],boi[1])]=1000*(l+1)+guy[3]
locs=[None]*(n**2)
for i in range(n):
    a=list(map(int,input().split()))
    for j in range(n):
        locs[a[j]-1]=(i,j)
best=(0,0,0)
for i in range(n**2-1):
    tup=(locs[i][0],locs[i][1],locs[i+1][0],locs[i+1][1])
    new0=min(best[0]+dists[0][0][tup],best[1]+dists[1][0][tup],best[2]+dists[2][0][tup])
    new1=min(best[0]+dists[0][1][tup],best[1]+dists[1][1][tup],best[2]+dists[2][1][tup])
    new2=min(best[0]+dists[0][2][tup],best[1]+dists[1][2][tup],best[2]+dists[2][2][tup])
    best=(new0,new1,new2)
a=min(best)
print(a//1000,a%1000)


import sys
inf=1000000000
n=input()
a=[map(int, raw_input().split()) for i in range(n)]
move=[None]*3
move[0]=[[2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1]]
move[1]=[[i, i] for i in range(-n+1, n)]+[[i, -i] for i in range(-n+1, n)]
move[2]=[[i, 0] for i in range(-n+1, n)]+[[0, i] for i in range(-n+1, n)]
dis=[[[[[[[inf, 0] for to_piece in range(3)] for from_piece in range(3)] for to_y in range(n) ] for to_x in range(n)] for from_y in range(n)] for from_x in range(n)]
for from_x in range(n):
	for from_y in range(n):
		for from_piece in range(3):
			q=[[from_x, from_y, from_piece]]
			first=0
			dis[from_x][from_y][from_x][from_y][from_piece][from_piece]=[0, 0]
			while first<len(q):
				cur_x, cur_y, cur_piece=q[first]
				first+=1
				cur_dis, cur_cnt=dis[from_x][from_y][cur_x][cur_y][from_piece][cur_piece]
				for move_x, move_y in move[cur_piece]:
					next_x, next_y=cur_x+move_x, cur_y+move_y
					if 0<=next_x<n and 0<=next_y<n and dis[from_x][from_y][next_x][next_y][from_piece][cur_piece]>[cur_dis+1, cur_cnt]:
						if dis[from_x][from_y][next_x][next_y][from_piece][cur_piece][0]==inf:
							q.append([next_x, next_y, cur_piece])
						dis[from_x][from_y][next_x][next_y][from_piece][cur_piece]=[cur_dis+1, cur_cnt]
				for to_piece in range(3):
					if dis[from_x][from_y][cur_x][cur_y][from_piece][to_piece]>[cur_dis+1, cur_cnt+1]:
						if dis[from_x][from_y][cur_x][cur_y][from_piece][to_piece][0]==inf:
							q.append([cur_x, cur_y, to_piece])
						dis[from_x][from_y][cur_x][cur_y][from_piece][to_piece]=[cur_dis+1, cur_cnt+1]
pos=[None]*(n*n+1)
for x in range(n):
	for y in range(n):
		pos[a[x][y]]=[x, y]
dp=[[[[inf, 0] for piece in range(3)] for y in range(n)] for x in range(n)]
dp[pos[n*n][0]][pos[n*n][1]]=[[0, 0], [0, 0], [0, 0]]
for value in range(n*n-1, 0, -1):
	cur_x, cur_y=pos[value]
	next_x, next_y=pos[value+1]
	for from_piece in range(3):
		for to_piece in range(3):
			a=dp[next_x][next_y][to_piece]
			b=dis[cur_x][cur_y][next_x][next_y][from_piece][to_piece]
			dp[cur_x][cur_y][from_piece]=min(dp[cur_x][cur_y][from_piece], [a[0]+b[0], a[1]+b[1]])
result=dp[pos[1][0]][pos[1][1]]
result=min(result[0], result[1], result[2])
print result[0], result[1]


config1=(raw_input()+raw_input()[::-1]).replace("X","")
config2=(raw_input()+raw_input()[::-1]).replace("X","")

if config2==config1 or config2==(config1[1]+config1[2]+config1[0]) or config2==(config1[2]+config1[0]+config1[1]):
	print "YES"
else:
	print "NO"


angle = int(input())
angle = (angle % 360 + 360) % 360
angle = (angle + 44) % 360
answer = (angle % 359) // 90
print(answer)


n = -input() % 360

if n == 0:
    print 0
else:
    ans = 0
    pos = min(abs(360 - n) ,abs(-n))

    for i in range(1,4):
        if min(abs(360 - (n + 90 * i)),abs(- (n + 90 * i))) < pos:
            ans = i
            pos = min(abs(360 - (n + 90 * i)),abs(- (n + 90 * i)))

    print ans


n = raw_input()
s = [x for x in raw_input()]
print "1" * int(s.count('1') > 0) + "0" * s.count('0')


n = input()
s = input()
s = ''.join(reversed(sorted(s)))
if s == '0':
    print(0)
    exit(0)
k = 0
for i in range(len(s)):
    if s[i] == '0':
        k += 1
if n == 1:
    print(s)
    exit(0)
ans = '1' + '0'*k
print(ans)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int,minp().split())

n,m,mi,ma = mints()
a = list(mints())
mii = min(a)
maa = max(a)
if mii > mi:
	m += 1
if maa < ma:
	m += 1
if mii < mi or maa > ma or m > n:
	print("Incorrect")
else:
	print("Correct")


n, m, v1, v2 = map(int, input().split())
t = list(map(int, input().split()))
t1, t2 = min(t), max(t)
if t1 < v1 or t2 > v2:
    print('Incorrect')
elif (v1 < t1) + (v2 > t2) > n - m:
    print('Incorrect')
else:
    print('Correct')


lemon = int(input()) ; apple = int(input()) ; pear = int(input())
fruits = 0
if lemon < 1 or apple < 2 or pear < 4:
    print(0)
    exit()
else:
    for i in range(lemon):
        if lemon >= 1 and apple >= 2 and pear >= 4:
            lemon -= 1 ; apple -= 2 ; pear -= 4
            fruits += 1 ; fruits += 2 ; fruits += 4
print(fruits)


a = int(input())
b = int(input())
c = int(input())

x = a
y = b // 2
z = c // 4

r =min(x , y , z)

print(r * 7 )


from fractions import Fraction
a,b,c,d=map(int,input().split())
# if(max(a,b)<max(c,d)):
#     z=Fraction(Fraction(a,b),Fraction(c,d))
# else:
#     z=Fraction(Fraction(c,d),Fraction(a,b))

# if((Fraction(1,1)-z)==0):
#     print("0/1")
# else:
#     print(Fraction(1,1)-z)

z1=Fraction(Fraction(a,b),Fraction(c,d))
z2=Fraction(Fraction(c,d),Fraction(a,b))

if((Fraction(1,1)-z1)==0):
    print("0/1")

else:
    x=Fraction(1,1)-z1
    if(x>0 and x<1):
        print(x)
    else:
        print(Fraction(1,1)-z2)


from math import gcd
from fractions import Fraction
def reduce_fraction(x,y):
    d = gcd(x,y)
    x = x // d
    y = y // d
    frac = Fraction(x/y).limit_denominator()
    print (frac)

a,b,c,d = map(int,input().split())
horizontal_space = (b*c - a*d)
vertical_space = (a*d - b*c)
flag = False
if horizontal_space == vertical_space:
    print("0/1")
    flag = True
elif horizontal_space > 0:
    numerator = horizontal_space
    denominator = b*c
elif vertical_space > 0:
    numerator = vertical_space
    denominator = a*d

if not flag:
    reduce_fraction(numerator , denominator)


import sys, array, bisect, collections, heapq, itertools, math, functools
sys.setrecursionlimit(100000)

def _r(): return sys.stdin.buffer.readline()
def rs(): return _r().decode('ascii').strip()
def rn(): return int(_r())
def rnt(): return tuple(map(int, _r().split()))
def rnl(): return list(rnt())
def rna(): return array.array('q', rnt())
def pnl(l): print(' '.join(map(str, l)))

def factorials_precalc(n, mod, inverse=True):
    fact = [1]*(n+1)
    rfact = [1]*(n+1) if inverse else None
    for i in range(1, n+1):
        fact[i] = fact[i-1] * i % mod;
        if inverse:
            rfact[i] = pow(fact[i], mod - 2, mod)
    return fact, rfact

mod = 998244353
fact, rfact = factorials_precalc(500, mod)

def binomial(n, k):
    return fact[n] * rfact[k] * rfact[n-k] % mod

@functools.lru_cache(maxsize=None)
def solve(n, x):
    if n == 1:
        return 0
    if x < n:
        return pow(x, n, mod)
    sol = pow(n-1, n, mod)
    for i in range(n-1):
        sol = (sol + fact[n] * rfact[i] * rfact[n-i] * pow(n-1, i, mod) * solve(n-i, x-n+1)) % mod
    return sol

print(solve(*rnt()))


from functools import lru_cache

MOD = 998244353
N, X = map(int, input().split())

r = 1

F = [1, 1]
for i in range(2, N+1):
    F.append((i * F[i-1]) % MOD)

IF = list(F)
IF[N] = pow(IF[N], MOD-2, MOD)
for i in range(N-1, 1, -1):
    IF[i] = IF[i+1] * (i+1)

def comb(n, k):
    return F[n] * IF[k] % MOD * IF[n-k] % MOD

@lru_cache(maxsize=None)
def g(n, x):
    if n == 1: return 0
    assert x >= 1

    dmg = n-1
    if dmg >= x:
        return pow(x, n, MOD)

    r = pow(dmg, n, MOD)
    for rem in range(2, n+1):
        #print('cur', n, 'rem', rem, 'x', x)
        attr = (comb(n, rem) * pow(dmg, n-rem, MOD) % MOD * g(rem, x-dmg)) % MOD
        #print(attr)
        r = (r + attr) % MOD

    #print(n, x, r)
    return r

"""
for i in range(2, X+1):
    for j in range(2, N+1):
        print(i, j)
        r = (r + comb(N, j) * pow(i-1, N-j, MOD)) % MOD
"""

print(g(N, X))


arr=[]
arr1=[]
arr2=[]
for i in range(0,4):
    x1,y1,x2,y2=map(int,input().split())
    p1=(x1,y1)
    p2=(x2,y2)
    p3=(x1,y1,x2,y2)
    arr2.append(p3)
    arr.append(p1)
    arr.append(p2)
arr1=list(set(arr))
if len(arr1)>4 or len(arr1)<4:
    print("NO")
    exit()
minx=10000000000
maxx=-10000000000
miny=10000000000
maxy=-10000000000
for i in range(0,len(arr1)):
    if minx>arr1[i][0]:
        minx=arr1[i][0]
    if maxx<arr1[i][0]:
        maxx=arr1[i][0]
    if miny>arr1[i][1]:
        miny=arr1[i][1]
    if maxy<arr1[i][1]:
        maxy=arr1[i][1]
arr3=[]
arr3.append((minx,miny,maxx,miny))
arr3.append((maxx,miny,maxx,maxy))
arr3.append((maxx,maxy,minx,maxy))
arr3.append((minx,maxy,minx,miny))
# print(arr3)
count=0
for i in range(0,4):
    for j in range(0,4):
        if arr3[i][0]==arr2[j][0] and arr3[i][1]==arr2[j][1] and arr3[i][2]==arr2[j][2] and arr3[i][3]==arr2[j][3]:
            count+=1
            break
            # print(arr3[i][0],arr3[i][1],arr3[i][2],arr3[i][3],arr2[i][0],arr2[i][1],arr2[i][2],arr2[i][3])
        elif arr3[i][2]==arr2[j][0] and arr3[i][3]==arr2[j][1] and arr3[i][0]==arr2[j][2] and arr3[i][1]==arr2[j][3]:
            count+=1
            break
            # print(arr3[i][0],arr3[i][1],arr3[i][2],arr3[i][3],arr2[i][0],arr2[i][1],arr2[i][2],arr2[i][3])
# print(count)
# print(arr2,arr3)
if count==4:
    print("YES")
else:
    print("NO")


def read_line():
  line = [int(item) for item in raw_input().split(" ")]
  return sorted([(line[0],line[1]), (line[2],line[3])])

lines = [read_line(), read_line(), read_line(), read_line()]

def is_vertical(line):
  return line[0][0] == line[1][0]

def is_horizontal(line):
  return line[0][1] == line[1][1]

def is_point(line):
  return (is_horizontal(line) and is_vertical(line))

points = [line for line in lines if is_point(line)]
hor = sorted([line for line in lines if is_horizontal(line)])
vert = sorted([line for line in lines if is_vertical(line)])

if not(len(hor) == 2 and len(vert) == 2):
  print "NO"
  exit()

if len(points) > 0:
  print "NO"
  exit()

if hor[0] == hor[1]:
  print "NO"
  exit()

if vert[0] == vert[1]:
  print "NO"
  exit()

#print hor
#print vert
#print lines

if hor[0][0] != min(vert)[0]:
  print "NO"
  exit()
if hor[0][1] != max(vert)[0]:
  print "NO"
  exit()
if hor[1][0] != min(vert)[1]:
  print "NO"
  exit()
if hor[1][1] != max(vert)[1]:
  print "NO"
  exit()

if vert[0][0] != min(hor)[0]:
  print "NO"
  exit()
if vert[0][1] != max(hor)[0]:
  print "NO"
  exit()

if vert[1][0] != min(hor)[1]:
  print "NO"
  exit()
if vert[1][1] != max(hor)[1]:
  print "NO"
  exit()

print "YES"


n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
curr = 0
for i in range(n):
    curr += a[i]
    mn = min(curr, 8)
    curr -= mn
    k -= mn
    if k <= 0:
        print(i+1)
        break
else:
    print (-1)


n, k = [int(x) for x in raw_input().split(' ')]
candiesArja = 0
candiesBran = 0
candies = [int(x) for x in raw_input().split(' ')]
for i in range(n):
    candiesArja += candies[i]
    currCandies = candiesArja if candiesArja <=8 else 8
    candiesBran += currCandies
    candiesArja -= currCandies
    if candiesBran >= k:
        print i+1
        break
else:
    print -1


import sys
import math

n = int(sys.stdin.readline())

v = [0] * n
ost = 1
if(n > 1):
    v[1] = 1
for i in range(1, n + 1):
    ost = (ost + i) % n
    v[ost] = 1

for i in v:
    if(i == 0):
        print("NO")
        exit()

print("YES")


n = int(raw_input())
z = 0
K = [0] * n

k = 0
x = 0
while x <= 1000:
    k += x
    while k >= n:
        k = k - n
    K[k] = 1
    x += 1
if 0 in K:
    print 'NO'
else:
    print 'YES'


n,k = map(int,raw_input().split())
a = (n/2) / (k+1)
b = k*a
print a,b,n-(a+b)


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

if n // 2 < k:
	print(0, 0, n)
else:
	a = n // 2 // (k + 1)
	b = n // 2 // (k + 1) * k
	print(a, b, n - a - b)


def fi(n):
    if n == 1:
        return x
    elif n == 2:
        return x + min(x, y)
    else:
        if n % 2 == 1:
            return min(fi(n-1), fi(n+1)) + x
        else:
            return fi(n//2) + min(y, x * (n//2))

n,x,y = map(int, input().split())
print(fi(n))


import sys

n, x, y = map(int, input().split())
size = 10**7
dq_x, dq_y, dq_i = [0]*size, [0]*size, [0]*size
l, r = 0, 0
cx, cy = 0, 0

for i in range(1, n+1):
    cx += 1
    while l < r and dq_i[l] < i:
        l += 1
    if l < r and (dq_x[l]-i-cx)*x + (dq_y[l]-cy)*y < 0:
        cx = dq_x[l] - i
        cy = dq_y[l]

    tx, ty = cx + i*2, cy+1
    while l < r and (dq_x[r]-tx)*x + (dq_y[r]-ty)*y > 0:
        r -= 1
    dq_x[r] = tx
    dq_y[r] = ty
    dq_i[r] = i*2
    r += 1

print(cx*x + cy*y)


#!/usr/bin/python
import sys
while True:
	s = sys.stdin.readline ().strip ()
	if s == '':
		s = sys.stdin.readline ().strip ()
		if s == '':
			break
	n = int (s)
	v = (n + 1) / 3
	print v / 12, v % 12


MOD = 10 ** 9 + 7

def pow(a, n):
    res = 1
    b = a
    while n != 0:
        if n % 2:
            res = (res * b) % MOD
        n //= 2
        b = (b * b) % MOD
    return res

assert pow(2, 10) == 1024
assert pow(7, 1) == 7
assert pow(7, 0) == 1

def egcd(a, b):
    assert a > 0 and b > 0

    a_orig = a
    b_orig = b

    x0, y0 = 1, 0
    x1, y1 = 0, 1

    assert a == a_orig * x0 + b_orig * y0
    assert b == a_orig * x1 + b_orig * y1

    while b != 0:
        q = a // b

        a, b = b, a - b * q
        x0, y0, x1, y1 = x1, y1, x0 - q * x1, y0 - q * y1

        assert a == a_orig * x0 + b_orig * y0
        assert b == a_orig * x1 + b_orig * y1

    return a, x0, y0

if False:
    print(egcd(3, 5))
    print(egcd(2, 4))
    print(egcd(4, 2))
    print(egcd(5, 3))

def solve(a, b, n, x):
    if a == 1:
        return (x + b * n) % MOD

    a_n = pow(a, n)
    one, inv_a_1, _ = egcd(a - 1, MOD)
    assert one == 1
    assert ((a - 1) * inv_a_1) % MOD == 1
    res = (a_n * x + b * (a_n - 1) * inv_a_1) % MOD

    return res

if False:
    assert solve(3, 4, 2, 1) == 25
    assert solve(3, 4, 1, 1) == 7
    solve(10 ** 9 - 19, 10 ** 9 - 23, 10 ** 18 - 57, 10 ** 9 - 16)
    assert solve(1, 4, 2, 10) == 18

else:
    a, b, n, x = map(int, input().split())
    print(solve(a, b, n, x))


a,b,n,x=map(int,raw_input().split())
mod=1000*1000*1000 +7
sum=0
if(a==1):
    sum=(x%mod+n*b%mod)%mod
else:
    sum=(pow(a,n,mod)*x+(((b*(pow(a,n,mod)-1))%mod)*pow(a-1,mod-2,mod))%mod)%mod

print(sum)


def check(x):
    if x== False:
        return 0
    else:
        return 1

x, y, z = map(int, input().split())
x1, y1, z1 = map(int, input().split())
a = list(map(int, input().split()))
ans = a[0]*check(y<0) + a[1]*check(y>y1) + a[2]*check(z<0) + a[3]*check(z>z1) + a[4]*check(x<0) + a[5]*check(x>x1)
print(ans)


rint = lambda: map (int, raw_input() .split ());

[a, b, c] = rint ();
[x, y, z] = rint ();
A = rint ();
B = [b, b - y, c, c - z, a, a - x];
d = [-1, 1, -1, 1, -1, 1];
ans = 0;

for i in xrange (6):
	if B[i] * d[i] > 0:
		ans += A[i];
print ans;


import re
import itertools

def get(c):
       return (ord(c) - ord('0') if '0' <= c <= '9' else ord(c) - ord('A') + 10)

def con(n, s):
      if n is '': return 0
      if get(n[-1]) >= s: return 100
      return get(n[-1]) + con(n[:-1], s) * s

def good(m, s):
      return con(m[0], s) < 24 and con(m[1], s) < 60

s = map(lambda x: max('0', re.sub('^0*', '', x)), raw_input().split(':'))
ans = filter(lambda x: good(s, x), range(100))
if len(ans) == 0: print '0'
elif len(ans) > 60: print '-1'
else: print ' '.join(str(x) for x in ans)


import string
import re

values={str(d): d for d in range(10) }
for ch in string.ascii_uppercase:
    values[ch] = ord(ch) - 55

def convert(s, i):
    x=0
    for ch in s:
        d = values[ch]
        if d>=i:
            return None
        x = i*x+d
    return x

match=re.match('0*(\w+):0*(\w+)',input().strip())
a,b=match.groups([1, 2])

ans = []
for i in range(2, 60):
    h = convert(a, i)
    m = convert(b, i)
    if h == None or m == None:
        continue
    if h < 24 and m < 60:
        ans.append(i)

if len(ans) == 0:
    print(0)
elif len(a) + len(b) == 2:
    print(-1)
else:
    print(*ans)


import sys
import math
import string
from collections import deque

# Function #
def read_int() :
    temp = raw_input().split();
    return map(int, temp);

def read_str() :
    temp = raw_input().split();
    return temp;

def write(output) :
    sys.stdout.write(output);

def writeln(output) :
    sys.stdout.write(str(output)+'\n');
# Class #

INF = 9123456789123456789
# Main Entry #

# Inner Function #

ans = set();

if __name__ == '__main__':

    def dfs(now, x, y) :
        if now <= tc :
            if now != 0 :
                ans.add(now);
            if now*10+x != 0 :
                dfs(now*10+x, x, y);
            if now*10+y != 0 :
                dfs(now*10+y, x, y);

    tc = read_int()[0];

    for ii in xrange(0, 10) :
        for jj in xrange(ii+1, 10) :
            dfs(0, ii, jj);

    print len(ans);

    pass
# End Here #


n = input()

if n <= 10:
	print n
else:
	cnt = 9
	le = len(str(n))
	i = 2
	while i <= le-1:
		cnt += ((81*((1<<(i-1))-1) + 9))
		i += 1

	d = {}

	for i in xrange(1,10):
		d[(int(str(i)*le))] = 1

	for i in xrange(1,10):
		for j in xrange(10):
			if i != j:
				mask = 0
				while mask < (1<<le-1):
					tmp = ""
					for k in xrange(le-1):
						if (mask&(1<<k)) > 0:
							tmp = str(i) + tmp
						else:
							tmp = str(j) + tmp
					tmp = str(i) + tmp
					d[(int(tmp))] = 1
					mask += 1

	for key in d:
		if key <= n:
			cnt += 1
	print cnt


#!/usr/bin/env python3

def solve():
    c, v0, v1, a, l = get([int])
    page = 0
    days = 0
    while page < c:
        page += v0 - (0 if page == 0 else l)
        v0 += a
        if v0 > v1:
            v0 = v1
        days += 1

    return days

_testcases = """
5 5 10 5 4

1

12 4 12 4 1

3

15 1 100 0 0

15

""".strip()

# ======================= B O I L E R P L A T E ======================= #
# Practicality beats purity

import re
import sys
import math
import heapq
from heapq import heapify, heappop, heappush
import bisect
import string
from bisect import bisect_left, bisect_right
import operator
from operator import itemgetter, attrgetter
import itertools
import collections

inf = float('inf')
sys.setrecursionlimit(10000)

def tree():
    return collections.defaultdict(tree)

def cache(func):  # Decorator for memoizing a function
    cache_dict = {}

    def _cached_func(*args, _get_cache=False):
        if _get_cache:
            return cache_dict
        if args in cache_dict:
            return cache_dict[args]
        cache_dict[args] = func(*args)
        return cache_dict[args]
    return _cached_func

def equal(x, y, epsilon=1e-6):
    # https://code.google.com/codejam/kickstart/resources/faq#real-number-behavior
    if -epsilon <= x - y <= epsilon:
        return True
    if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:
        return False
    return (-epsilon <= (x - y) / x <= epsilon or -epsilon <= (x - y) / y <= epsilon)

def get(_type):  # For easy input
    if type(_type) == list:
        if len(_type) == 1:
            _type = _type[0]
            return list(map(_type, input().strip().split()))
        else:
            return [_type[i](inp) for i, inp in enumerate(input().strip().split())]
    else:
        return _type(input().strip())

if __name__ == '__main__':
    print(solve())


c, v0, v1, a, l = map(int, input().split())
cur = cnt = 0
while cur < c:
    cur = max(0, cur - l)
    cur += min(v1, v0 + a * cnt)
    cnt += 1
print(cnt)


x1, x2, a, b = map(int, input().split())
if a <= 0 <= b:
    if x1 < x2:
        if x2 - x1 <= b:
            print("FIRST")
            print(x2)
        else:
            print("DRAW")
    else:
        if x1 - x2 <= -a:
            print("FIRST")
            print(x2)
        else:
            print("DRAW")
else:
    reverse = False
    if a < 0:
        x1, x2, a, b = -x1, -x2, -b, -a
        reverse = True
    if x1 > x2:
        print("DRAW")
    else:
        if (x2 - x1) % (a + b) == 0:
            print("SECOND")
        elif a <= (x2 - x1) % (a + b) <= b:
            print("FIRST")
            print((x1 + (x2 - x1) % (a + b))
                  if not reverse else -(x1 + (x2 - x1) % (a + b)))
        else:
            print("DRAW")


x1,x2,a,b=map(int,raw_input().split())
if x1+a<=x2<=x1+b: print 'FIRST'; print x2
elif a<=0<=b: print 'DRAW'
elif a>0:
    if x1>x2: print 'DRAW'
    else:
        s=(x2-x1)%(a+b)
        if s==0: print 'SECOND'
        elif a<=s<=b: print 'FIRST';print x1+s
        else: print 'DRAW'
else:
    if x1<x2: print 'DRAW'
    else:
        s=abs(x1-x2)%abs(a+b)
        if s==0: print 'SECOND'
        elif -b<=s<=-a: print 'FIRST';print x1-s
        else: print 'DRAW'


n = int(raw_input())
s = raw_input().strip()
ans = n
i = 0
while i < n-1:
    if s[i] + s[i+1] in ["RU", "UR"]:
        ans -= 1
        i += 2
    else:
        i += 1
print ans


n = int(input())
s = list(input())
i = 1
total = 0
if n == 1:
    print(1)
else:
    while i < n:
        if (s[i-1] + s[i] == "UU") or (s[i-1] + s[i] == "RR"):
            total += 1
            i += 1
        elif (s[i-1] + s[i] == "UR") or (s[i-1] + s[i] == "RU"):
            total += 1
            i += 2
        if i == n:
            total += 1
    print(total)


import bisect
import array
n,m=list(map(int,input().split()))
a=array.array('L',map(int,input().split()))
a1,a2=array.array('L'),array.array('L')
n1=n//2

def sums1(i,sum=0):
    if i==n1:
        a1.append(sum)
    else:
        sums1(i+1,(sum+a[i])%m)
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        a2.append(sum)
    else:
        sums2(i+1,(sum+a[i])%m)
        sums2(i+1,sum)
k=0
sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=array.array('L',sorted(set(a1)))

for i in a2:
    j=bisect.bisect_left(a1,m-i)
    if ans<a1[j-1]+i:
        ans=a1[j-1]+i
print(ans)


import sys
import bisect

def gen(start, end, ar, distinct_values, value, mod):
    if start == end:
	distinct_values.add(value)
	return

    gen(start + 1, end, ar, distinct_values, value, mod)
    gen(start + 1, end, ar, distinct_values, (value + ar[start])%mod, mod)

def main():
    n, m = map(int, raw_input().split())
    ar = map(int, raw_input().split())

    first, second = set(), set()
    gen(0, n//2, ar, first, 0, m)
    gen(n//2, n, ar, second, 0, m)

    first = sorted(first)
    second = sorted(second)
    print max(x + second[bisect.bisect_left(second, m - x) - 1] for x in first)

if __name__ == '__main__':
    main()


n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
import bisect
a1,a2=[],[]
n1=n//2

def sums1(i,sum=0):
    if i==n1:
        a1.append(sum)
    else:
        sums1(i+1,(sum+a[i])%m)
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        a2.append(sum)
    else:
        sums2(i+1,(sum+a[i])%m)
        sums2(i+1,sum)

sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=sorted(set(a1))

for i in a2:
    j=bisect.bisect_left(a1,m-i)
    ans=max(ans,a1[j-1]+i)
    k=a1[j-1]+i
    if ans<k:
        ans=k
print(ans)


import bisect
import array
n,m=list(map(int,input().split()))
a=array.array('L')
a.extend(map(int,input().split()))
a1,a2=array.array('L'),array.array('L')
n1=n//2

def sums1(i,sum=0):
    if i==n1:
        a1.append(sum)
    else:
        sums1(i+1,(sum+a[i])%m)
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        a2.append(sum)
    else:
        sums2(i+1,(sum+a[i])%m)
        sums2(i+1,sum)

sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=array.array('L',sorted(set(a1)))

for i in a2:
    j=bisect.bisect_left(a1,m-i)
    if ans<a1[j-1]+i:
        ans=a1[j-1]+i
print(ans)


n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
a=[int(i) for i in input().split()]
import bisect
a1,a2=[],[]
n1=n//2

def sums1(i,sum=0):
    if i==n1:
        a1.append(sum)
    else:
        sums1(i+1,(sum+a[i])%m)
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        a2.append(sum)
    else:
        sums2(i+1,(sum+a[i])%m)
        sums2(i+1,sum)

sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=sorted(set(a1))

for i in a2:
    j=bisect.bisect_left(a1,m-i)
    if ans<a1[j-1]+i:
        ans=a1[j-1]+i
print(ans)


n,m=map(int,input().split())
a=[int(i) for i in input().split()]
x,y=set(),set()
def f(x,n,i,s=0):
    if i==n:
        if s == m - 1: exit(print(s))
        x.add(s)
    else:
        f(x,n,i+1,(s+a[i])%m)
        f(x,n,i+1,s)
h=n//2
f(x,h,0)
f(y,n,h)
y=sorted(y)
import bisect
k=0
print(max(i+y[bisect.bisect_left(y,m-i)-1]for i in x))


n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
import bisect
a1,a2=[],[]
n1=n//2
app1=a1.append
app2=a2.append
def sums1(i,sum=0):
    if i==n1:
        app1(sum)
    else:
        sums1(i+1,(sum+a[i])%m)
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        app2(sum)
    else:
        sums2(i+1,(sum+a[i])%m)
        sums2(i+1,sum)

sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=sorted(set(a1))
bis=bisect.bisect_left
for i in a2:
    j=bis(a1,m-i)
    if ans<a1[j-1]+i:
        ans=a1[j-1]+i
print(ans)


n,m=map(int,input().split())
a=[int(i)%m for i in input().split()]
x,y=set(),set()
def f(x,n,i,s=0):
    if i==n:
        x.add(s)
    else:
        f(x,n,i+1,(s+a[i])%m)
        f(x,n,i+1,s)
h=n//2
f(x,h,0)
f(y,n,h)
y=sorted(y)
import bisect
k=0
print(max(i+y[bisect.bisect_left(y,m-i)-1]for i in x))


# -*- coding: utf-8 -*-
from itertools import imap
from heapq import merge
from bisect import bisect

def readline(): return imap(int, raw_input().split())

class Solved(Exception):
    pass

def get_values(a, m):
    values = [(0, 1)]
    for v in a:
        new_values1, new_values2 = [], []
        for (x, y) in values:
            x1, y1 = x + v, y + v
            if x1 < m:
                if y1 < m:
                    new_values1.append((x1, y1))
                else:
                    print(m - 1)
                    raise Solved
            else:
                new_values2.append((x1 - m, y1 - m))

        new_values = []
        hx, hy = 0, 1
        for pair in merge(values, new_values1, new_values2):
            if hy >= pair[0]:
                hy = pair[1]
            else:
                new_values.append((hx, hy))
                hx, hy = pair
        values = new_values + [(hx, hy)]
    return values

def main():
    n, m = tuple(readline())
    a = filter(bool, (x % m for x in readline()))

    mid = (n + 1) >> 1
    a1, a2 = a[:mid], a[mid:]

    try:
        v1, v2 = get_values(a1, m), get_values(a2, m)
    except Solved:
        return

    ans = max(max(v1)[1] - 1, max(v2)[1] - 1)

    for (x, y) in v2:
        if ans == m - 1:
            break
        idx = bisect(v1, (m - x, 0))
        if not idx:
            break
        y1 = v1[idx - 1][1]
        ans = max(ans, m - 1 if y1 - 1 >= m - y else y - 1 + y1 - 1)

    print(ans)

main()


n,m=map(int,input().split())
l=[int(i) for i in input().split()]
first=l[:n//2]
sec=l[n//2:]
n1=n//2
n2=n//2+n%2
t1=(1<<n1)
t2=(1<<n2)
s1=[]
for i in range(t1):
    now=0
    for j in range(len(first)):
        if i&(1<<j):
            now+=first[j]
    s1.append(now%m)
s2=[]
for i in range(t2):
    now= 0
    for j in range(len(sec)):
        if i&(1<<j):
            now+=sec[j]
    s2.append(now%m)
s1.sort()
s2.sort()
maxi=0
def check(l,x): #largest number less than x in l  # l is asc
    lo=0
    hi=len(l)-1
    ans=0
    while lo<=hi:
        mi=(lo+hi)>>1
        if l[mi]<x:
            ans=l[mi]
            lo=mi+1
        else:
            hi=mi-1
    return ans
for i in s1:
    req=m-i
    pair=check(s2,req)
    maxi=max(maxi,(i+pair)%m)
print(maxi)


n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
import bisect
a1,a2=[],[]
n1=n//2
app1=a1.append
app2=a2.append
def sums1(i,sum=0):
    if i==n1:
        app1(sum%m)
    else:
        sums1(i+1,(sum+a[i]))
        sums1(i+1,sum)

def sums2(i,sum=0):
    if i==n:
        app2(sum%m)
    else:
        sums2(i+1,(sum+a[i]))
        sums2(i+1,sum)

sums1(0)
sums2(n1)

ans=0
end=len(a2)-1

a1=sorted(set(a1))
bis=bisect.bisect_left
def solve(i):
    global ans
    j=bis(a1,m-i)
    if ans<a1[j-1]+i:
        ans=a1[j-1]+i
    return ans
l=list(map(solve,a2))
print(l[-1])


# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction

mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
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")

# -------------------game starts now----------------------------------------------------import math
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):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        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

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
        """initialize the segment tree with data"""
        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)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        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)

# -------------------------------iye ha chutiya zindegi-------------------------------------
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)  # To make sure already calculated n^-1
        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

# --------------------------------------iye ha combinations ka zindegi---------------------------------
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

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

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

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <= key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

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

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
l=list(map(int,input().split()))
l=[l[i]%k for i in range(n)]
if n==1:
    print(l[0])
    sys.exit(0)
l1=l[:n//2]
l2=l[n//2:]
s=set()
s1=set()
s2=set()
for i in range(n//2):
    for j in s:
        s2.add((j+l1[i])%k)
    s.add(l1[i])
    for j in s2:
        s.add(j)
    s2=set()
for i in range(n-n//2):
    for j in s1:
        s2.add((j+l2[i])%k)
    s1.add(l2[i])
    for j in s2:
        s1.add(j)
    s2 = set()
s=list(s)
s1=list(s1)
s.sort()
s1.sort()
ans=max(max(s),max(s1))
for i in range(len(s)):
    t=k-1-s[i]
    ind=binarySearchCount(s1,len(s1),t)
    r=s1[ind-1]
    rt=s1[-1]
    t=ans
    ans=max((r+s[i])%k,(s[i]+rt)%k)
    ans=max(ans,t)
    #print(ans,t)
print(ans)


a, b = map(int, input().split(" "))
aa, bb = bin(a)[2:], bin(b)[2:]

ans = 0
if len(aa) == len(bb):
    s = ["1"]*len(aa)
    for i in range(1, len(s)):
        s[i] = "0"
        ss = int("".join(s), 2)
        if ss >= a and ss <= b:
            ans += 1
        s[i] = "1"
else:
    s = ["1"]*len(aa)
    for i in range(1, len(s)):
        s[i] = "0"
        ss = int("".join(s), 2)
        if ss >= a:
            ans += 1
        s[i] = "1"
    s = ["1"]*len(bb)
    for i in range(1, len(s)):
        s[i] = "0"
        ss = int("".join(s), 2)
        if ss <= b:
            ans += 1
        s[i] = "1"
    for i in range(len(aa)+1, len(bb)):
        ans += i-1

print(ans)


x = input().split()

hazZero = False

binary = bin(int(x[0]))
binary = binary[2:]

for i in range(len(binary)):
    if (binary[i] == '0'):
        hazZero = True

if (not hazZero):
    binary = bin(int(x[0]) + 1)
    binary = binary[2:]

isFirst = True
new_binary = ''

for i in range(len(binary)):
    if (binary[i] == '0'):
        if (isFirst):
            new_binary = new_binary + '0'
            isFirst = False
        else:
            new_binary = new_binary + '1'
    else:
        new_binary = new_binary + binary[i]

inDecimal = int(new_binary, 2)

total = 0

while (int(x[0]) <= inDecimal and inDecimal <= int(x[1]) ):
    total += 1
    if (new_binary == '1'):
        total -= 1
        new_binary = '10'
    elif (new_binary[-1] == '0'):
        new_binary = '10' + new_binary[:-1]
    else:
        new_binary = '1' + new_binary[:-1]
    inDecimal = int(new_binary, 2)

print(total)


n,l,r,x = map(int,input().split())
a = list(map(int,input().split()))
count=0
for i in range(2**n):
    maxc=-1
    minc=-1
    c=0
    for j in range(n):
        if i>>j&1==1:
            c+=a[j]
            maxc=max(maxc,a[j])
            if minc==-1:
                minc=a[j]
            else:
                minc=min(a[j],minc)
    if c>=l and c<=r and maxc - minc >=x:
        count+=1
print(count)


from sys import stdin
from itertools import combinations
n, l, r , x = map(int, stdin.readline().rstrip().split(" "))
li = list(map(int, stdin.readline().rstrip().split(" ")))
z = []
ans = 0
for i in range(2, n+1):
    z += list(combinations(li, i))

for i in z:
    a = sorted(i)
    if a[-1]-a[0]>=x and r >= sum(a) >= l:
        ans+=1

print(ans)


input=__import__('sys').stdin.readline
for _ in range(int(input())):
    n=int(input())
    i=2
    while i*i<=n and n%i!=0:
        i+=1
    if i*i>n:
        print(1,n-1)
    else:
        print(n//i,n//i*(i-1))


for t in range(int(input())):
    n=int(input())
    test=0
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            test=1
            break
    if test==1:

        a=n//i
        b=n-a
    else:
        a=1
        b=n-1
    print(a,b)


import sys
def device(n,m):
    if m < n :
        return n-m
    elif m == n :
        return 0
    else :
        dic = {n:0}
        level = 1
        frontier = [n]
        current = 1000000000
        while frontier :
            new = []
            l = len(frontier)
            for i in range(0,l) :
                num = frontier.pop()
                num1 = num - 1
                if num1 == m :
                    return level
                if num1 not in dic :
                    dic[num1] = 0
                    new.append(num1)

                num2 = num*2
                if num2 == m :
                    return level
                elif num2 > m :
                    current = min(current, num2-m + level)
                elif num2 not in dic :
                    dic[num2] = 0
                    new.append(num2)
            frontier = new
            level = level + 1
            if level >=current :
                return current

n,m = map(int,sys.stdin.readline().split())
print device(n,m)


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

count = 0
while m > n:
	if m == 2*n:
		n = m
	elif m%2:
		m += 1
	else:
		m = m//2

	count += 1

count += n-m

print(count)


import sys

seent = {}

def vect(x, k):
  if (x in seent):
    return

  seent[x] = k
  if (x % 2 == 0):
    vect(x / 2, k + 1)
  if (x % 3 == 0):
    vect(x / 3, k + 1)
  if (x % 5 == 0):
    vect(x / 5, k + 1)

def orr(x, k):
  if (x in seent):
    if (seent[x] == -1):
      return -1
    else:
      return k + seent[x]

  seent[x] = -1

  mn = float("inf")
  if (x % 2 == 0):
    ret = orr(x / 2, k + 1)
    if (ret != -1):
      mn = min(ret, mn)

  if (x % 3 == 0):
    ret = orr(x / 3, k + 1)
    if (ret != -1):
      mn = min(ret, mn)

  if (x % 5 == 0):
    ret = orr(x / 5, k + 1)
    if (ret != -1):
      mn = min(ret, mn)

  if (mn == float("inf")):
    return -1
  return mn

a, b = [ int(x) for x in sys.stdin.readline().strip().split() ]
vect(a, 0)
print orr(b, 0)


v1, v2 = map(int, raw_input().split())
t, d = map(int, raw_input().split())

arr = [0] * t
arr[0], arr[-1] = v1, v2

for i in xrange(-2, -t, -1):
	arr[i] = arr[i + 1] + d

for i in xrange(1, t - 1):
	arr[i] = min(arr[i], arr[i - 1] + d)

print sum(arr)


v1,v2 = map(int,raw_input().split())
t,d = map(int,raw_input().split())
dp = [0] * t
dp[0] = v1
dp[-1] = v2
for i in xrange(t-2,0,-1):
	dp[i] = min(dp[-1] + (t-1)*d-(i*d),dp[0] + i*d)
print sum(dp)


A = map(int, raw_input().split())
B = map(int, raw_input().split())
C = map(int, raw_input().split())

AB = (B[0] - A[0], B[1] - A[1])
AC = (C[0] - A[0], C[1] - A[1])

p = AB[0] * AC[1] - AC[0] * AB[1]

if p == 0:
    print('TOWARDS')
elif p > 0:
    print('LEFT')
elif p < 0:
    print('RIGHT')
else:
    raise ValueError


def vec(a, b):
    return a[0] * b[1] - a[1] * b[0]

a_x, a_y = [int(i) for i in input().split()]
b_x, b_y = [int(i) for i in input().split()]
c_x, c_y = [int(i) for i in input().split()]
a, b, c = [a_x, a_y], [b_x, b_y], [c_x, c_y]
s, d = [b[0] - a[0], b[1] - a[1]], [c[0] - a[0], c[1] - a[1]]
e = vec(s, d)
if e < 0:
    print('RIGHT')
elif e > 0:
    print('LEFT')
else:
    print("TOWARDS")


TUX = input()
FOO = 0
BAR = 0
BAZ = 0
QUZ = 1
TUX = int(TUX)
while TUX != 0:
    PUR = input()
    PUR = int(PUR)
    FOO = FOO + PUR
    BAR = BAR + 1
    #if max(FOO * QUZ, BAR
    if max(FOO * QUZ, BAR * BAZ) == FOO * QUZ:
    #if BOTH SAEM BIGGR OF PRODUKT OF FOO AN QUZ AN PRODUKT OF BAR BAZ AN PRODUKT OF FOO AN QUZ:
        BAZ = FOO
        QUZ = BAR
    TUX = TUX - 1
BAZ = int(BAZ)
print(BAZ / QUZ)


TUX=int(input())
FOO=0
BAR=0
BAZ=0
QUZ=1
for i in range(TUX):
  PUR=int(input())
  FOO=FOO+PUR
  BAR=BAR+1
  if FOO*QUZ>BAZ*BAR:
    BAZ=FOO
    QUZ=BAR
print(BAZ/QUZ)


from queue import Queue as Q
n, x = map(int, input().split())
q = Q()
q.put((x, 0))
was = set()
while not q.empty():
    r = q.get()
    if r[0] >= 10**(n-1):
        print(r[1])
        break
    else:
        for i in str(r[0]):
            if i not in [0, 1]:
                new = int(i)*r[0]
                if new not in was:
                    was.add(new)
                    q.put((new, r[1]+1))
else:
    print(-1)


import gc
import heapq
import itertools
import math
import sqlite3
from collections import Counter, deque, defaultdict
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import threading
from heapq import *
from fractions import Fraction

def S():
    return sys.stdin.readline().split()

def I():
    return [int(i) for i in sys.stdin.readline().split()]

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

def IS():
    return sys.stdin.readline().replace('\n', '')

def main():
    n, a = I()

    m = [(float('inf'), -1) for _ in range(n + 10)]
    queue = deque([(a, 0)])
    m[len(str(a))] = (0, a)
    _dict = defaultdict(bool)
    _dict[a] = True
    while queue:
        c, q = queue.pop()
        for d in set(str(c)):
            if int(d) > 1:
                new_c = c * int(d)
                str_c = str(new_c)
                if m[len(str_c)][0] > q + 1:
                    m[len(str_c)] = (q + 1, new_c)
                _set = [int(i) for i in str_c]
                if not (max(_set) < 2 or len(str_c) >= n or _dict[new_c]):
                    _dict[new_c] = True
                    queue.appendleft((new_c, q + 1))

    print(m[n][0] if m[n][0] < float('inf') else -1)

if __name__ == '__main__':
    # for _ in range(II()):
    #     main()
    main()


from sys import stdin
s=stdin.readline().strip()
k=int(stdin.readline().strip())
n=len(s)
dp=[[[[ None for tt in range(2)]for i in range(2)] for j in range(k+1)] for k1 in range(n)]
dp1=[[[[ None for tt in range(2)]for i in range(2)] for j in range(k+1)] for k1 in range(n)]

def sol(i,j,t,c):
    if i==n:
        if j!=0:
            return -10000000
        else:
            return 0

    if dp[i][j][t][c]!=None:
        return dp[i][j][t][c]
    ans=0
    if c==-1:
        c=(s[i]=="F")
    if c:
        if t:
            ans=-1+sol(i+1,j,t,-1)
        else:
            ans=1+sol(i+1,j,t,-1)
        if j>0:
            ans=max(ans,sol(i,j-1, t,0))
    else :
        ans=sol(i+1,j,not t,-1)
        if j>0:
            ans=max(ans,sol(i,j-1, t,1))
    dp[i][j][t][c]=ans
    return dp[i][j][t][c]
def sol1(i,j,t,c):
    if i==n:
        if j!=0:
            return 10000000
        else:
            return 0
    if dp1[i][j][t][c]!=None:
        return dp1[i][j][t][c]
    ans=0
    if c==-1:
        c=(s[i]=="F")
    if c:
        if t:
            ans=-1+sol1(i+1,j,t,-1)
        else:
            ans=1+sol1(i+1,j,t,-1)
        if j>0:
            ans=min(ans,sol1(i,j-1, t,0))
    else :
        ans=sol1(i+1,j,not t,-1)
        if j>0:
            ans=min(ans,sol1(i,j-1, t,1))
    dp1[i][j][t][c]=ans
    return dp1[i][j][t][c]
print(max(sol(0,k,0,-1),-sol1(0,k,0,-1)))


n, m = map(int, input().split(' '))
G = [[0]*n for i in range(n)]

for i in range(m):
    u, v = map(lambda x:int(x)-1, input().split(' '))
    G[u][v] = G[v][u] = 1

s = [' ']*n

for i in range(n):
    if G[i].count(1) == n-1:
        s[i] = 'b'

try:
    anode = s.index(' ')
    s[anode] = 'a'
except:
    print('Yes')
    print(''.join(s))
    exit()

for i in range(n):
    if s[i] == ' ' and G[anode][i] == 1:
        s[i] = 'a'
    elif s[i] == ' ' and G[anode][i] == 0:
        s[i] = 'c'

for i in range(n):
    for j in range(i+1, n):
        if (s[i] != s[j] and s[i] != 'b' and s[j] != 'b') == G[i][j]:
                print('No')
                exit()

print('Yes')
print(''.join(s))


# http://codeforces.com/contest/623/problem/A

import math

nm = raw_input()
nm = nm.split(' ')
n = int(nm[0])
m = int(nm[1])

edges = [[False for i in range(n)] for x in range(n)]   # False: no such edge
nodes = [[True for i in range(3)] for x in range(n)]    # True: possible

# read edges
for i in range(m):
  ab = raw_input()
  ab = ab.split(' ')
  a = int(ab[0]) - 1
  b = int(ab[1]) - 1
  edges[a][b] = True
  #print 'add edge:',a,b

def hasEdge(a,b):
  if edges[a][b] or edges[b][a]:
    return True
  else:
    return False

# True if has deduction
def deduce(n1,n2):
  # if has edge, same
  if hasEdge(n1,n2) and certain(n1):
    val_1 = get(n1)
    # n1 is 'a', n2 isn't 'c'
    if val_1 == 0 and nodes[n2][2] :
      nodes[n2][2] = False
      #print 'node',n2,'is a'
      return True
    # n1 is 'c', n2 isn't 'a'
    if val_1 == 2 and nodes[n2][0]:
      nodes[n2][0] = False
      #print 'node',n2,'is a'
      return True
  # if no edge, different
  elif not hasEdge(n1,n2) and certain(n1):
    val_1 = get(n1)
    if val_1 == 0 and nodes[n2][0]:
      nodes[n2][0] = False
      #print 'node',n2,'is c'
      return True
    if val_1 == 2 and nodes[n2][2]:
      nodes[n2][2] = False
      #print 'node',n2,'is a'
      return True
  return False

def deductions():
  for i in range(n):
    for j in range(n):
      if i != j:
        deduce(i,j)

# only has one possibility
def certain(k):
  if (nodes[k][0] + nodes[k][1] + nodes[k][2]) == 1:
    return True
  return False

def freeNode(k):
  if (nodes[k][0] + nodes[k][1] + nodes[k][2]) == 3:
    return True
  return False

def isDeadNode(k):
  if (nodes[k][0] + nodes[k][1] + nodes[k][2]) == 0:
    return True
  return False

# get the node first possible node, not certain
def get(k):
  if nodes[k][0]:
    return 0
  if nodes[k][1]:
    return 1
  if nodes[k][2]:
    return 2

def incompleteSolution():
  for k in range(n):
    if not certain(k):
      return k
  return False

def genSolution():
  tmp = incompleteSolution()
  # loop if node id returned
  while isinstance(tmp, int):
    deductions()
    tmp = incompleteSolution()

def printSolution():
  ss = []
  for i in range(n):
    theChar = get(i)
    if theChar == 0:
      theChar = 'a'
    elif theChar == 1:
      theChar = 'b'
    else:
      theChar = 'c'
    ss.append(theChar)
  print ''.join(ss)

# main
# no edge, no b
complete = True
firstMissingEdge = []
for i in range(n):
  for j in range(n):
    if (i != j) and not hasEdge(i,j):
      #print 'no edge: ',i,j
      if complete:
        complete = False
        firstMissingEdge.append(i)
        firstMissingEdge.append(j)
      #print 'missing edge',i,j
      # must not b
      nodes[i][1] = False
      nodes[j][1] = False

# if free node => is b
for i in range(n):
  if freeNode(i):
    nodes[i][0] = False
    nodes[i][2] = False
    #print 'node',i,'is \'b\''

# complete graph
if complete:
  ss = []
  for i in range(n):
    ss.append('b')
  print 'Yes'
  print ''.join(ss)

else:
  # 1. guess one node to be 'a'
  a = firstMissingEdge[0]
  b = firstMissingEdge[1]
  nodes[a][2] = False   # node[a] be 'a'
  nodes[b][0] = False   # node[b] be 'c'
  #print 'let node',a,'be a, node',b,'be c'
  # loop check, deduction...
  updated = True
  hasDeadNode = False
  while updated:
    updated = False
    for i in range(n):
      for j in range(n):
        if i != j:
          if deduce(i,j):
            updated = True
          if isDeadNode(j):
            hasDeadNode = True
            break
      if hasDeadNode:
        break
    if hasDeadNode:
      break

  if hasDeadNode:
    print 'No'
  else:
    print 'Yes'
    printSolution()


dr = [1,2,2,1,-1,-2,-2,-1,0]
dc = [2,1,-1,-2,2,1,-1,-2,0]

rook = list(raw_input())
rook[0] = ord(rook[0]) - ord('a') + 1
rook = map(int,rook)

knight = list(raw_input())
knight[0] = ord(knight[0]) - ord('a') + 1
knight = map(int,knight)

numPlaces = 0
for i in xrange(1,9):
	for j in xrange(1,9):
		isAttacked = False
		for k in xrange(len(dr)):
			if (i+dr[k] == rook[1] and j+dc[k] == rook[0]) or (i+dr[k] == knight[1] and j+dc[k] == knight[0]) or i == rook[1] or j == rook[0]:
				isAttacked = True
				break
		if isAttacked == False:
			numPlaces += 1

print numPlaces


def Count (n):
    cnt = 0
    x = 1
    while True:
        if x > n:
            break
        y = 1
        while True:
            if x * y > n:
                break
            cnt += 1
            y *= 3
        x *= 2
    return cnt

def Result (l, r):
    if l == 0:
        return Count (r)
    return Count (r) - Count (l - 1)

l, r = map (int, input ().split ())
print (Result (l, r))


l,r = list(map(int, input().split()))
ans = 0
for i in range(40):
    for j in range(40):
        v= int(2**i * 3**j);
        if(v >= l and v <= r):
            ans = ans + 1

print(ans)


global dp
def solve(a,l,r,d):
    if r-l+1 <= 1:
        return 0
    curD = a[r]-a[l]
    if curD <= d:
        return 0
    if dp[l][r]!=-1:
        return dp[l][r]

    dp[l][r] = min( 1+solve(a,l+1,r,d), 1+solve(a,l,r-1,d) )
    return dp[l][r]

dp = [[ -1 for i in range(100)] for j in range(100)]
n, d = map(int,input().split())
a = list(map(int,input().split()))
a = sorted(a)
ans = solve(a,0,n-1,d)
print(ans)


n,d=input().split()
n=int(n)
d=int(d)
l=[int(x) for x in input().split()]
l.sort()
mindel=0
mini=0
maxi=n-1
for i in range(n):
    for j in range(n-1, -1, -1):
        if abs(l[j]-l[i])<=d and abs(j-i)>mindel:
            mini=i
            maxi=j
            mindel=abs(j-i)
if abs(l[maxi]-l[mini])>d:
    print(n-1)
else:
    print(mini+n-maxi-1)


'''
    Author : thekushalghosh
    Team   : CodeDiggers
'''
import sys,math
input = sys.stdin.readline
n = int(input())
q = [1,2]
for i in range(24):
    if q[-1] % 2 != 0:
        q = q + [q[-1] + q[-2],q[-1] + q[-2] + 1]
    else:
        q = q + [(2 * q[-1]),(2 * q[-1]) + 1]
if n in q:
    print(1)
else:
    print(0)


n = int(input())
arr = list(map(int,input().split()))
arr.append(-100000000000)
arr.append(1000000000000)
i = 0
while(arr[i] < arr[i+1] and i < n-1):
	i = i + 1

while(arr[i] == arr[i+1] and i < n-1):
	i = i + 1

while(arr[i] > arr[i+1] and i < n-1):
	i = i + 1

if(i == n-1):
	print("YES")

else:
	print("NO")


#http://codeforces.com/problemset/problem/831/A
def main(n,lst):
	if(n==1):
		return "YES"
	#0-increasing, 1-staying, 2-decreasing
	if(lst[0]<lst[1]):
		status=0
	elif(lst[0]==lst[1]):
		status=1
	else:
		status=2
	for i in range(len(lst)-1):
		if(status==0):
			if(lst[i]==lst[i+1]):
				status+=1
			if(lst[i]>lst[i+1]):
				status+=2
		if(status==1):
			if(lst[i]>lst[i+1]):
				status+=1
			if(lst[i]<lst[i+1]):
				return "NO"
		if(status==2):
			if(lst[i]>lst[i+1]):
				pass
			else:
				return "NO"
	return "YES"

n=eval(input())

lst=input().split()
lst=[eval(i) for i in lst]
print(main(n,lst))


def f(n, k):
    n0, s = n, 0
    while n > 0:
        s += min(n, k)
        n -= min(n, k)
        n -= n // 10
    return s * 2 >= n0

def g(n):
    lo, hi = 1, n
    while lo < hi:
        mid = (lo + hi) // 2
        if f(n, mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

print(g(int(input())))