def dfs(grid, x, y):
    if [x, y] == [0, 0]:
        toggle(x+1,y)
        toggle(x,y+1)

    if [x, y] == [0, 1]:
        toggle(x,y-1)
        toggle(x+1,y)
        toggle(x,y+1)

    if [x, y] == [0, 2]:
        toggle(x,y-1)
        toggle(x+1,y)

    if [x, y] == [1, 0]:
        toggle(x-1,y)
        toggle(x+1, y)
        toggle(x, y+1)

    if [x, y] == [1, 1]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x+1, y)
        grid[x][y+1] = toggle(x, y+1)

    if [x, y] == [1, 2]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x+1, y)

    if [x, y] == [2, 0]:
        toggle(x-1 , y)
        toggle(x, y+1)

    if [x, y] == [2, 1]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x, y+1)

    if [x, y] == [2, 2]:
        toggle(x-1 , y)
        toggle(x , y-1)

    toggle(x, y)

def toggle(x, y):
    if result[x][y] == 1:
        result[x][y] = 0
    else:
        result[x][y] = 1

grid = []
result = []
for i in range(3):
    grid.append([int(x) for x in input().split()])
    result.append([1 for x in range(3)])

for row in range(3):
    for col in range(3):
        if grid[row][col] == 0:
            continue

        val = grid[row][col]
        if val % 2 == 0:
            continue
        else:
            dfs(grid, row, col)

for row in range(3):
    for col in range(3):
        print(result[row][col)
    print()


t=int(input())
while(t):
    t-=1
    n=int(input())
    l=list(map(int,input().strip().split()))
    ct=0

    for i in range(1,n):
        if(l[i]==1):
            if(l[i-1]==2):
                ct+=3
            else:
                ct+=4
        elif(l[i]==2):
            if(l[i-1]==1):
                if(i>=2 and l[i-2]==3):
                    ct+=2
                else:
                    ct+=3
            else:
                ct=-1
        else:
            if(l[i-1]==1):
                ct+=4
            else:
                ct=-1
        if(ct==-1):
            print('Infinite')
            break
    if(ct!=-1):
        print('Finite')
        print(ct)


a= int(input())
b=input()
l=b.split()
q=b.split()
s=[]
k=[]
def max(l):
    t=l[0]
    f=t
    for j in range(1,len(l)):
        if l[j]>t:
            f=l[j]
    return f

for i in range(1,len(l)-1):
    v=l[i]
    del l[i]
    for j in range(len(l)-1):
        p=int(l[j+1])-int(l[j])
        s.append(p)
    w=max(s)
    k.append(w)
    l.append(v)
    l.sort()

h=min(k)
print(h


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

_min = 1000 * 2
diff = 0

for i in range(n -1):
    _min = min(_min, l[i] + l[i+1])
    diff = max(l[i-1] - l[i])

print max(diff, _min)


n = int(input())
k = int(input())
M = int(input())
D = int(input())
ans = 0
for i in range(D + 1):
        maxX = n // (i * k - k + 1)
        minX = n // (i * k + 1)
        if n % (i * k + 1) == 0 :
            minX += 1
        maxX = min(maxX, M)
        if minX <= maxX:
            ans = max(ans, i * maxX)
print(ans)


def main():
    M=998244353
    n,k,*h=map(int,open(0).read().split())
    m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
    f=[0]*(m+1)
    f[0]=b=1
    for i in range(1,m+1):f[i]=b=b*i%M
    inv=[0]*(m+1)
    inv[m]=b=pow(f[m],M-2,M)
    for i in range(m,0,-1):inv[i-1]=b=b*i%M
    comb=lambda n,k:f[n]*inv[n-k]*inv[k]%M
    print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*inv[2]%M)
main()


from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *

#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# 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")

#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------

farr=[1]
ifa=[]

def fact(x,mod=0):
    if mod:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr)%mod)
    else:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr))
    return farr[x]

def ifact(x,mod):
    global ifa
    ifa.append(pow(farr[-1],mod-2,mod))
    for i in range(x,0,-1):
        ifa.append(ifa[-1]*i%mod)
    ifa=ifa[::-1]

def per(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return fact(i)//fact(i-j)
    return farr[i]*ifa[i-j]%mod

def com(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return per(i,j)//fact(j)
    return per(i,j,mod)*ifa[j]%mod

def catalan(n):
    return com(2*n,n)//(n+1)

def linc(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t>f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rinc(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t<f(mid):
            r=mid-1
        else:
            l=mid
    return l

def ldec(f,t,l,r):
    while l<r:
        mid=(l+r)//2
        if t<f(mid):
            l=mid+1
        else:
            r=mid
    return l

def rdec(f,t,l,r):
    while l<r:
        mid=(l+r+1)//2
        if t>f(mid):
            r=mid-1
        else:
            l=mid
    return l

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def binfun(x):
    c=0
    for w in arr:
        c+=ceil(w/x)
    return c

def lowbit(n):
    return n&-n

def inverse(a,m):
    a%=m
    if a<=1: return a
    return ((1-inverse(m,a)*m)//a)%m

class BIT:
    def __init__(self,arr):
        self.arr=arr
        self.n=len(arr)-1

    def update(self,x,v):
        while x<=self.n:
            self.arr[x]+=v
            x+=x&-x

    def query(self,x):
        ans=0
        while x:
            ans+=self.arr[x]
            x&=x-1
        return ans

class smt:
    def __init__(self,l,r,arr):
        self.l=l
        self.r=r
        self.value=(1<<31)-1 if l<r else arr[l]
        mid=(l+r)//2
        if(l<r):
            self.left=smt(l,mid,arr)
            self.right=smt(mid+1,r,arr)
            self.value&=self.left.value&self.right.value
        #print(l,r,self.value)
    def setvalue(self,x,val):
        if(self.l==self.r):
            self.value=val
            return
        mid=(self.l+self.r)//2
        if(x<=mid):
            self.left.setvalue(x,val)
        else:
            self.right.setvalue(x,val)
        self.value=self.left.value&self.right.value
    def ask(self,l,r):
        if(l<=self.l and r>=self.r):
            return self.value
        val=(1<<31)-1
        mid=(self.l+self.r)//2
        if(l<=mid):
            val&=self.left.ask(l,r)
        if(r>mid):
            val&=self.right.ask(l,r)
        return val

class DSU:#容量+路径压缩
    def __init__(self,n):
        self.c=[-1]*n

    def same(self,x,y):
        return self.find(x)==self.find(y)

    def find(self,x):
        if self.c[x]<0:
            return x
        self.c[x]=self.find(self.c[x])
        return self.c[x]

    def union(self,u,v):
        u,v=self.find(u),self.find(v)
        if u==v:
            return False
        if self.c[u]<self.c[v]:
            u,v=v,u
        self.c[u]+=self.c[v]
        self.c[v]=u
        return True

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

class UFS:#秩+路径
    def __init__(self,n):
        self.parent=[i for i in range(n)]
        self.ranks=[0]*n

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

    def union(self,u,v):
        pu,pv=self.find(u),self.find(v)
        if pu==pv:
            return False
        if self.ranks[pu]>=self.ranks[pv]:
            self.parent[pv]=pu
            if self.ranks[pv]==self.ranks[pu]:
                self.ranks[pu]+=1
        else:
            self.parent[pu]=pv

def Prime(n):
    c=0
    prime=[]
    flag=[0]*(n+1)
    for i in range(2,n+1):
        if not flag[i]:
            prime.append(i)
            c+=1
        for j in range(c):
            if i*prime[j]>n: break
            flag[i*prime[j]]=prime[j]
            if i%prime[j]==0: break
    return prime

def dij(s,graph):
    d={}
    d[s]=0
    heap=[(0,s)]
    seen=set()
    while heap:
        dis,u=heappop(heap)
        if u in seen:
            continue
        for v in graph[u]:
            if v not in d or d[v]>d[u]+graph[u][v]:
                d[v]=d[u]+graph[u][v]
                heappush(heap,(d[v],v))
    return d

def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)]

class DLN:
    def __init__(self,val):
        self.val=val
        self.pre=None
        self.next=None

t=1
for i in range(t):
    mod=998244353
    n,k=RL()
    h=RLL()
    res=GP(h)
    c=0
    for ch,cnt in res:
        c+=cnt-1
    n=len(res)
    if n>1 and res[-1][0]==res[0][0]:
        c+=1
        n-=1
    ans=pow(k,c,mod)
    tmp=pow(k,n,mod)
    fact(n,mod)
    ifact(n,mod)
    p=[1]
    for i in range(n):
        p.append(p[-1]*(k-2)%mod)
    for x in range(n//2+1):
        tmp=(tmp-p[n-2*x]*fact(n,mod)%mod*ifa[x]%mod*ifa[x]%mod*ifa[n-2*x]%mod)%mod
    ans=ans*tmp%mod*pow(2,mod-2,mod)%mod
    print(ans)


a, b = map(int, input().split())
arra = []
for i in range(b - a):
    arra.append(a + 1 + i)
b = 1
for i in range(len(arra)):
    b *= arra[i]
print(b % 10)


s=input()
u=0
l=0
for i in s:
   if i.isupper():
     u+=1
   if i.islower()
     l+=1
if u>l:
  print(s.upper())
if u<l:
 print(s.lower())
else:
 print(s.upper())


n, m = map(int, input().split())
ans = n // 5 * 5 * (m // 5)
x = n // 5
y = m // 5
x1 = n % 5
y1 = m % 5
ans += x1 * y + y1 * x
for i in range(1, x1 + 1):
    for j in range(1, y + 1):
            if (i + j) % 5 == 0:
                ans++
print(ans)


import sys

inp = input().split()
    m = inp[0]
    n = inp[1]
    m_5 = m % 5
    n_5 = n % 5
    res = m*n//5
    for i in range(m_5):
        for j in range(n_5):
            if i+j % 5 == 0:
                res += 1

    print(res)


def main():
    n = int(input())
    print((int(input()) - 2) ** 2)

if __name__ == '__main__':
    main()


n,m=map(int,input().split(" "))
if n*m<6:
    print(0)

elif n*m==6:
    print(4)
elif (n==2 and m%2==1) or (m==2 and n%2==1):
    print(n*m-2)
elif((n==2 and m%2==0) or (m==2 and n%2==0))
    print(n*m)
else:
    print(n*m-(n*m)%2)


n,m=map(int,input().split())
v=0
for b in sorted((list(map(int,input().split()))[::-1] for i in range(m), reverse=True):
    c=min(b[1],n)
    n-=c
    v+=c*b[0]
print(v)


n=int(input())
a=list(map(int,input().split()))
curr=0
prod,count=1,0
last=a.index(1)
for i in range(0,n):
	if(a[i]==1):
		count+=1
		if(i!=a.index(1)):
			last=curr
		curr=i
		if(i!=a.index(1)):
			prod*=(curr-last)
if(count!=0):
	print(prod)
else:
	print(0)


n, m = map(int, input().split() )
x = min(n, m // 2)
print(x + (n + m - 3*x)//3 if n > x else x)


name = input()

if  name[0] in  "w, m, j, e, b, r, s, v, n, k, p, l, u, i, q":
    print("CHAT WITH HER!")
else:
    name[1] in "w":
    print("IGNORE HIM!")


import sys

MIN = -1000000000
x, y, z, k = [int(x) for x in sys.stdin.readline().split()]
x1, y1, z1 = 1, 1, 1
for i in range(k):
    a, b, c = MIN, MIN, MIN
    if x1 < x:
        a = (x1+1)*y1*z1
    if y1 < y:
        b = x1*(y1+1)*z1
    if z1 < z:
        c = x1*y1*(z1+1)
    best = max(a, b, c)
    if best == MIN:
        break
    if best == a:
        x1 += 1
    elif best == b:
        y1 += 1
    else:
        z1 += 1
#print(x1,y1,z1)
print(x1*y1*z1)


x,y,z=map(int,input().split())
if (x-(y+z))*((x+z)-y)<0:
    print('?)
else:
    if x-(y+z)>0:
        print('+')
    elif (x+z)-y<0:
        print('-')
    else:
        print('0')


import math
def phi(n):
    res = n
    for i in range(2, int(math.sqrt(n)) + 1):
        if(n % i == 0):
            while(n % i == 0):
                n /= i
            res -= res/i
    if(n > 1):
        res -= int(res / n)
    return res
n, k = map(int, input().split())
res = n
k = int((k + 1) / 2)
while(res != 1 and k != 0):
    res = phi(n)
    k -= 1
print("{}".format(int(res % (1e9 + 7))))


MOD = 1000000007
def phi(n):
    res = n
    for i in range(2,int(n**(0.5)+1)):
        if n % i == 0:
            while n % i == 0:
                n = n//i
            res -= res//i
    if n > 1:
        res -= res//n
    return res

n,k = map(int,input().split())
k = (k+1)//2
ans = n
for _ in range(k):
    ans = phi(ans)
print(ans % MOD)


from itertools import product, chain
from collections import Counter

dic = {}
dic[1] = ['4', '7']
dic[2] = ['44', '47', '74', '77']

def getperm(n):
	if n in dic:
		return dic[n]
	dic[n] =  [''.join(e) for e in chain(product(getperm(n-2), getperm(n-1)))]
	return dic[n]

s = str(int(raw_input()))

if s in ['7',  '4']:
	print(s)

elif len(s) == 1:
	print('-1')

else:

	ans = '-1'
	val = 0
	for n in range( 1,  s.count('4') + s.count('7')):

		for c in getperm(n):
			cc = s.count( c )

			if val < cc:
				ans = c
				val = cc

	print ( ans )


a = input().strip()
a = a + ''.join(list(reversed(input().strip())))

b = input().strip()
b = b + ''.join(list(reversed(input().strip())))

a = a.replace('X', '')
b = b.replace('X', '')
f = False
for i in range(4):
    if a == b:
        f = True
    b = b[1:] + b[:1]
if f:
    print("YES")
else:
    print("NO")


friend1=int(input())
friend2=int(input())
counter1=1
counter2=1
tiredness=0
while friend1!=friend2:
  friend1+=1
  tiredness+=counter1
  counter1+=1
  if friend1==friend2:
   break
  friend2-=1
  tiredness+=counter2
  counter2+=1

print(tiredness)


num = [x for int(x) in input().split()]

n = num[0]
m = num[1]
a = num[2]
b = num[2]

while True:
    if count > n:
        low = count - m
        high = count
        break
    count += m

des = b * (n - low)
build = a * (high - n)

pay = max([des, build])
print(pay)


while(true)
	n=input()
	m=input()
	a=input()
	b=input()

	cost=0

	if n%m==0:
		print(cost)
	else:
		k=(n%m)*b
		f=(m-(n%m))*a
		cost=min(k,f)
		print(cost)


n = int(input())
if n > 21 orn <= 10:
     print(0)
else:
     if n >= 11 and n <= 19:
          print(4)
     else:
          if n == 20:
               print(15)


n, m = input().split()
n = int(n)
m = int(m)
print(m % (2**n))


from math import ceil,floor

FILE = "rectangle_puzzle"
try:
    inFile = open(FILE+".txt")
except:
    pass

def read():
    try:
        return inFile.readline().strip()
    except:
        return raw_input().strip()

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

n,m,x,y,a,b = map(int,read().split())
g = gcd(a,b)
a /= g
b /= g

s = min(m/a,n/b)

x1 = (2*x-s*a)/2
x2 = x1 + s*a
if x1 < 0:
    x2 += -x1
    x1 = 0
elif x2 > n:
    x1 -= (x2-n)
    x2 = n

y1 = (2*y-s*b)/2
y2 = y1 + s*b
#print y1,y2
if y1 < 0:
    y2 += -y1
    y1 = 0
elif y2 > m:
    y1 -= (y2-m)
    y2 = m

print x1,y1,x2,y2


def gcd(a,b): return a if (b==0) else gcd(b,a%b)
n,m,x,y,a,b=map(int,raw_input().split())
d=gcd(a,b)
k=min(n*d/a,m*d/b)
p,q=a*k,b*k
c,d=min(n-p,max(x-(p+1)/2,0)),min(m-q,max(y-(q+1)/2,0))
print c,d,c+p,d+q


n = int(input())
k = int(input())
a = int(input())
b = int(input())
dp = [-1 for i in range(n+1)]
dp[1]=0
for i in range(2,n+1):
    if(i%k==0):
        dp[i]=min(dp[i-1]+a,dp[i//k]+b)
    else:
        dp[i] = dp[i-1]+a
print(dp[n])
#basic dp  ------------ GOD save me from TLE


w,x=map(int,input().split())
lst=[]
for i in range(0,30):
    if  pow(w,i)<x*2:
        lst.append(pow(w,i))

n=len(lst)
lst.sort(reverse=True)
ans=100000
def rec(a,x,i):
    #print a
    global ans
    if a==x:
        ans=1
        return 1

    if i==n:
    #ans=-1
        return
    rec(a,x,i+1)

    rec(a-lst[i],x,i+1)
    rec(a+lst[i],x,i+1)

   # print a

if w==2:
    print ("YES")
else:

    rec(0,x,0)

    if ans==100000 :
      print ("NO")
    else:
      print ("YES")


w,m=map(int,input().split())
ans=[0]
for k in range(100):
 p=w**k
 if p>m*m: break
 t=[x+p for x in ans]
 r=[x-p for x in ans]
 ans.extend(t)
 ans.extend(r)

print("YES" if m in ans else "NO")


w, h = map(int, input().split())
u, d = map(int, input().split())
u1, d1 = map(int, input().split())
m = w + h + d + d1
p = u + u1
if m - p > 0:
    print(m - p)
elif h == 0:
    print(w)
else:
    prinr(0)


 _ = input().strip().split(' ')
n = int(_[0])
p = int(_[1])
k = int(_[2])
# print(n, p, k)
cnt = p - k
if cnt < 1:
    cnt = 1
if cnt != 1:
    print('<< ',end='')
while cnt <= n and cnt <= (p + k):
    if cnt == p:
        print('(%d) '%cnt, end='')
    else:
        print(cnt, end=' ')
    cnt += 1
if cnt-1 != n:
    print('>>')


a, b = list(map(int, input().split()))
l = [1]

if a == 0:
    a = 1

for i in range(2, b + 1):
    l.append(l[-1] * i)

g = str(int(l[b - 1] / l[a - 1]))

print(g[-1])


#!/usr/bin/env python2

occ = []
for i in range(300):
    occ.append(0)
pair = {}
k = 0
i = 0
while i < 300:
    while i < 300 and occ[i] == 1:
        i += 1
    if i == 300:
        break
    occ[i] = 1
    if i+k < 300:
        occ[i+k] = 1
    pair[i] = i+k
    k += 1
#print pair

n = int(raw_input())

if n == 1:
    a = int(raw_input())
    if a == 0:
        print "BitAryo"
    else:
        print "BitLGM"

elif n == 2:
    a, b = map(int, raw_input().split())
    if pair[a] == b or pair[b] == a:
        print "BitAryo"
    else:
        print "BitLGM"

else:
    a, b, c = map(int, raw_input().split())
    if (a^b^c) == 0:
        print "BitAryo"
    else:
        print "BitLGM"


dp=[]
for i in xrange(333):
    tmp = []
    for j in xrange(333):
        tmp.append(-1)
    dp.append(tmp)

def win(a,b):
    if(dp[a][b]!=-1):return dp[a][b]
    if(a+b==0): return 0
    can = 0
    if a>0:
     for i in xrange(a):
        if(win(i,b)==0): can=1
    if(b>0):
        for i in xrange(b):
            if(win(a,i)==0): can = 1

    if(min(a,b)>=1):
     for i in xrange(min(a,b)):
        if(win(a-i-1,b-i-1)==0): can=1
    dp[a][b]=can
    return dp[a][b]

n = map(int,raw_input().split())[0]
a = map(int,raw_input().split())
s1="BitLGM"
s2="BitAryo"

if n==2:
    if win(a[0],a[1])==1:
        print s1
    else: print s2
    exit(0)

t = 0
if n==1: t = a[0]
else:
    t = (a[0]^a[1]^a[2])

if(t>0):
    print s1
else:
    print s2


def main():
    n,k = list(map(int, input().split()))
    b = list(map(int, input().split()))
    b.sort(reverse = True)
    for x in b:
        if k % x == 0:
            print (k // num)
            return
main()


n=input()
s=input()
i=1
while s[i-1]=='1':
	i+=1
	if i==len(s):
		break
print(i)


n=int(input())
s=input()
if s[0]=='0':
    print(1)
else:
    i=1
    while i<len(s) and s[i]=='1':
        i+=1
if i<len(s) and s[i]=='0':
    i+=1
print(i)


n,k = map(int,input().split())
s=[1]
t =[2]
for i in range(1,n):
    s = s + t + s
    t[0]=t[0]+1
print(s[k-1])


n,k=map(int,input().split())
l=[1]
for i in range(1,n):
    ll=[]
    ll.extend(l)
    ll.append(i+1)
    ll.extend(l)
    l=ll
# print(l)
print(l[k-1])


def kodok(n):
	balikan = []
	for i in range(1, n+1):
	    balikan = balikan + [i] + balikan
	return balikan
def main():
    a = input('')
    n = int(a.split()[0])
    k = int(a.split()[1])
    print(kodok(n)[k-1])

main()


n,k=map(int,input().split())
l=[1]
v=2
for i in range(n-1) :
    l=l+[v]+l
    v=v+1
print(l[k-1])


n1 = input()
m = n1.split(' ')
n = int(m[0])
k = int(m[1])

ans = []
b = 1
for i in range(1,n+1):
	lala = []
	j = b
	while (j < 2**n) :
		lala.append(j)
		j += 2*b
	b = b*2
	ans.append(lala)
#print(ans)
for me in ans:
	for you in me:
		#print(you)
		if (you == k) : print(ans.index(me)+1)
		if (you == k) : break
	if (you == k) : break


n,k = list(map(int,input().split()))
def fun(n,k):
    a=[1]
    for i in range(n-1):
      a+=a
      a.insert(((2**(i+1))-1),i+2)
    print(a[k-1])
fun(n,k)


n, k = map(int, input().split())
use = [2]
arr = [1]
for i in range(1, n):
    arr = arr + use + arr
    use[0] += 1

print(arr[k - 1])


n, k = [int(x) for x in input().split()]
a = [1]
c = 2
while n > 1:
    current = a
    a.append(c)
    a = a + current[:len(a) - 1]
    n -= 1
    c += 1
if len(a) < k:
    print(a[k % len(a) - 1])
else:
    print(a[k - 1])


from copy import deepcopy
n, k = [int(x) for x in input().split()]

if k & 1:
    print(1)
else:
    a = [1]
    pp = 2
    for i in range(n):
        cc = deepcopy(a)
        a.append(pp)
        a = a + cc
        pp += 1
    if k > len(a):
        print(a[len(a) % k - 1])
    else:
        print(a[k - 1])


n,k=map(int,raw_input().split())
a=[1]
i=1
while i<n:
    a=a[:]+[i+1]+a[:]
    i+=1
print a[k-1]


from sys import stdin
a = [1]
j = 2
n ,k = map(int,stdin.readline().split())
while True:
    b = a + [j] + a
    a = list(b)
    if len(a)>k:
        break
    j+=1
    if j > n:
        break
print a[k-1]


n,k=map(int,raw_input().split())
a=[1]
for i in xrange(n):
    a=a+[max(a)+1]+a
print a[k-1]


n,k=raw_input().split()
n=int(n)
k=int(k)

seq=[1]

for i in range(2,n+1):
    seq = seq + [i] + seq

print seq[k-1]


import copy
n,k = map(int,raw_input().split())
l = [1,2,1]
m = copy.copy(l)
some = 3
for i in range(n-2):
    l += [some]
    l += m
    m = copy.copy(l)
    some += 1
print l[k-1]


x=raw_input().split()
n=int(x[0])
k=int(x[1])

def func(n):
    if n<=1:
        return [1]
    x=func(n-1)

    l=[]
    l.extend(x)
    l.append(n)
    l.extend(x)
    return l

print func(n)[k-1]


n,k=raw_input().split()
n=int(n)
k=int(k)
if n>1:
	n=n-2
	a="1 2 1"
	i=3
	while n>0:
		a=a+" "+str(i)+" "+a
		i=i+1
		n=n-1
	b=a.split()
	print b[k-1]
else:
	print "1"


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


n = int(input())
s = input()

def parse(pr, tail):
    if tail == '':
        return 1
    s = "CYM" if tail[0] == '?' else tail[0]
    count = 0
    for c in s:
        if c != pr:
            count += parse(c, tail[1:])
        if count > 1:
            return count
    return count
s = s.replace("????", "???")
print("Yes" if parse('', s)>1 else "No")


n = int(raw_input())

ans = n + 1
j = 2

while j <= n - 1 :
    ans = ans + j * (n - j - 1)

print ans


from collections import *
n = int(input())
s = input()
b = [int (i) for i in input().split(' ')]
n = n
cnt = defaultdict(int)
multiples = []
biggest = 'a'
ans = 0
for i in range(n//2):
    if(s[i] == s[n-i-1]):
        multiples.append(i)
        cnt[s[i]] += 1
        ans += max(b[i],b[n-i-1])
    else:
        ans += b[i] + b[n-i-1]

for i in range(26):
    if(cnt[chr(ord('a')+i)] > cnt[biggest]):
        biggest = chr(ord('a')+i)
more = max(max(cnt.values())*2-sum(cnt.values()),0)
# print(more)
takes = []
for i in range(n//2):
    if(s[i] != biggest and s[n-i-1] != biggest):
        takes.append(min(b[i],b[n-i-1]))

takes = sorted(takes)[:more]
pen = sum(takes)
# print(pen)
# print(takes)
print(ans-pen)


#https://pymotw.com/2/collections/counter.html
#same code as mmaxio
from collections import Counter

r = lambda: map(int, input().split())

def main():
	n, = r()
	s = input()
	cost = list(r())

	ans = 0

	cnt = Counter()

	for i in range(n // 2):
		if s[i] == s[n - 1 - i]:
			ans += min(cost[i], cost[n - 1 - i])
			cnt[s[i]] += 1
	total = sum(cnt.values())
	if total > 0:
		ch, occ = cnt.most_common(1)[0]
		avail = []
		if occ > total - occ:# if highest occurence is more than the 50% of total then we will look for the letters which does not have pairs and are not equal to the letter with the highest ocuurence
			for i in range(n // 2):
				if s[i] != s[n - 1 - i] and s[i] != ch and s[n - 1 - i] != ch:
					avail.append(min(cost[i], cost[n - 1 - i]))
			avail=sorted(avail,reverse=True)
			ans += sum(avail[:2 * occ - total])

	print(sum(cost)-ans)

main()
#suppose total is 100 and highest occ is 51...difference between highest occ and remaining can be found using this form 2*occ-total as it is a simplified form of two steps 1.total-occ=remaining and 2.occ-remaining which is this case is 2 if highest occ is <= 50 % of total then it can be satisfied by remaining 50% but if it is greater than 50% then we have to use the letters of of the total


x, y = [int(x) for x in input().split()]
n = int(input())
f = []
for i in range (n + 1):
    f.append(0)
f[1] = x
f[2] = y
for i in range (3, n + 1, 1):
    f[i] = f[i - 1] - f[i - 2]
print(f[n] % (10 ** 9 + 7))


x,y=map(int,input().split())
n=int(input())
a=[x,y]
for i in range(1,n):
    a.append(a[i]-a[i-1])
print(a[n-1]%1000000007)


n, m = map(int, input().split())
a1, s1 = list(map(int, input().split())), list(map(int, input().split()))
a2, s2, a, s = [], [], [], []
for q in range(0, n*2, 2):
    a2.append([a1[q], a1[q+1]])
for q in range(0, m*2, 2):
    s2.append([s1[q], s1[q + 1]])
for q in range(n):
    k = set()
    for q1 in range(m):
        if len(set(a2[q]) & set(s2[q1])) == 1:
            k.add(list(set(a2[q]) & set(s2[q1]))[0])
    if k:
        a.append([a2[q][0], a2[q][1], list(k)])
for q in range(m):
    k = set()
    for q1 in range(n):
        if len(set(s2[q]) & set(a2[q1])) == 1:
            k.add(list(set(s2[q]) & set(a2[q1]))[0])
    if k:
        s.append([s2[q][0], s2[q][1], list(k)])
z, p = set(), float('inf')
for q in range(len(a)):
    if len(a[q][2]) > 1:
        print(-1)
        p = -1
        break
    z.add(a[q][2][0])
else:
    if len(z) > 1:
        p = 1
    z = set()
    for q in range(len(s)):
        if len(s[q][2]) > 1:
            print(-1)
            p = -1
            break
        z.add(a[q][2][0])
    else:
        if len(z) > 1 or p == 1:
            print(0)
        else:
            print(list(z)[0])


a,b = [int(x) for x in raw_input().split()]
V = [0] * a
for i in range(0,b):
    inp = int(raw_input())
    for i in range( inp - 1 , a):
        if V[i] == 0 :
            V[i] = inp

for i in range (0 , a):
    print V[i],


import sys
def buttons(n, m, array):
    answer = [0] * n
    for index, item in enumerate(array):
        for i in range(item - 1, n):
            if answer[i] == 0:
                answer[i] = item
    for i in range(len(answer)):
        print str(answer[i]),
def main():
    n = int(sys.argv[1])
    m = int(sys.argv[2])
    array = []
    for i in range(m):
        i += 3
        array += [int(sys.argv[i])]
    buttons(n, m, array)
if __name__ == "__main__":
    main()


n = int(input())
d = str(n)
a = []
t = n
if(n<10):
    print(n)
else:
    flag = 0
    while(n>9):
        a.append(9)
        t = n%10
        if(t != 9):
            flag = 1
        n //= 10
    s = n
    #print(s,t,flag)
    a.append(n-1)
    if(a[-1] != 0):
        a1 = 1
        a2 = 1
        if(flag == 0):
            for i in range(1,s+1):
                for j in range(1,10):
                    if((i==s and j<=t) or (i<s)):
                        if(i*j > a1*a2):
                            a1 = i
                            a2 = j
        else:
            for i in range(1,s+1):
                for j in range(1,10):
                    if((i==s and j<t) or (i<s)):
                        if(i*j > a1*a2):
                            a1 = i
                            a2 = j
        #print(a1,a2)
        a[-1] = a1
        a[-2] = a2
    else:
        a[-1] = 1
    ans = 1

    if(a[-3] == 9 and a[-2] == 7 and d[1] >= '8' and d[2] >= '9'):
        a[-2] = 8
        a[-3] = 8
    #print(a)
    for i in a:
        ans *= i
    print(ans)


def stages()
	n=int(input())
	k=int(input())
	s=input()
	w=0
	count1=0
	count2=0
	x=[]
	for i in range(n):
		x.append(ord(s[i])-96)
	x.sort()
	j=x[0]
	w+=x[0]
	for l in range(n):
		if x[l]-j>=2 and x[l]<=26:
			j=x[l]
			count1+=1
			if count1<=k-1:
				w+=x[l]
				count2+=1
	if count2==k-1:
		print(w)
	else:
		print(-1)


n,k = map(int,input())
s = input()

s = ''.join(sorted(s))

def cost(c):
	return ord(c) - ord('a')

curr = 0
total = cost(s[curr])
count = 1

for i in range(1:n):
	if count == k:
		break
	if cost(s[i]) - cost(s[curr]) >= 2:
		total += cost(s[i])
		count += 1
		curr = i
if count == k:
	print(total)
else:
	print(-1)


n=int(input())
arr=list(map(int,input().split()))
freq=[0]*(101)
freq2=[0]*(101)
ans=0
for i in range(n):
  freq[arr[i]]+=1
  if i>=1:
    freq3=[]
    for k in range(1,101):
     if freq[k]>=1:
      freq3.append(freq[k])
    #print(freq3)
    if freq3.count(max(freq3))>=2:
      ans=max(ans,i+1)
for j in range(n):
  freq2[arr[j]]+=1
  freq3=[]
  for k in range(1,101):
   if freq[k]>=1:freq3.append(freq[k]-freq2[k])
  #print(freq3,j+1)
  if max(freq3)>0 and freq3.count(max(freq3))>=2:
      ans=max(ans,n-j-1)
      #print()
      break
print(ans)


from collections import Counter
n = int(input())
A = list(map(int, input().split()))
cnt = Counter(A)
maxv = max(cnt.values())
x = [c for c in cnt if cnt[c] == maxv]
if len(x) > 1:
    print(n)
else:
    x = x[0]
    ans = 0
    for c in cnt:
        if c == x: continue
        B = [1 if a == c else -1 if a == x else 0 for a in A]
        dic = {0: -1}
        cur = 0
        tmp = 0
        for i, b in enumerate(B):
            cur += b
            if cur in dic:
                tmp = max(tmp, i - dic[cur])
            dic.setdefault(cur, i)
        ans = max(ans, tmp)
    print(ans)


# n - length of zebroid
def cnt_subzebroes(n):
        if n > 0:
                cnt = 1
        else:
                cnt = 0
        dict = {}
        dict[n], dict[n + 1] = 0, 0
        last = n - 1
        while last > 0:
                dict[last] = dict[last + 1] + dict[last + 2] + 1
                cnt = cnt + dict[last] + 1
                last -= 1
	return cnt % 1000000007

print cnt_subzebroes(int(input()))


n = int(input())
i = 1
m = 0
while i <= n:
    if n % i == 0:
        j = 0
        while j <= i:
            a = pow(2, j) - 1
            b = pow(2, j - 1)
            if a * b == i:
                if i > m:
                    m = i
            j += 1
    i += 1
print(m)


a,b,c,d=map(int,input().split()))
s=0
p=min(a,c,d)
s+=p*256
a-=p
q=min(b,a)
s+=32*q
print(s)


n = int(raw_input())
count = 0
anslist = []
for i in range(n):
    s = str(i)
    add = 0
    for l in s:
        add += int(l)
    add+=i
    if int(add) == n:
        anslist.append(i)
        count+=1
print count
for t in anslist:
    print t\


i = int(raw_input(''))
wyn = 0
wyn_part = 0
tab = []
for x in range(0, i, +1):
    str_x = str(x)
    suma = 0
    for y in range(0, len(str_x),+1):
        suma += int(str_x[y])
    if x + suma == i:
        wyn += 1
        tab.append(x)
print wyn
for z in range(0, len(tab),+1):
    print tab[z]


import math

candidate = [1,5,10,50]

n = int(input())

res = candidate + []

if n == 1:
    print(len(res))
else:
    for i in range(n-1):
        now = []
        for j in candidate:
            for k in range(len(res)):
                now.append(res[k] + j)
        res = list(set(now))
    print(len(res))


from sys import stdin, stdout

def count(n):
    d = {}
    cnt = 0
    cur = 0

    for i in range(n + 1):
        for j in range(n - i + 1):
            for z in range(n - j - i + 1):
                v = i * 1 + j * 5 + z * 10 + (n - i - j - z) * 50

                if not v in d:
                    d[v] = 1
                    cur += 1
                else:
                    d[v] += 1

    return cur

n = int(stdin.readline())

for i in range(20, 200):
    n = i

    if count(i) != count(20) + 49 * (i - 20):
        print(i)

if n >= 20:
    upp = count(20) + 49 * (n - 20)
else:
    upp = count(n)
print(upp)


b,g,n=int(input()),int(input()),int(input())
m=min(b,g)
ma=max(b,g)
if m>= n :
	print (n+1):
else if ma>= n:
	print (m+1)
else:
	print (ma-m+1)


x,y,n=map(int,input().split())
if (y<=n):
    print(str(x)+"/"+str(y))
else:
    print(str(x-1)+"/"+str1(n-1))


luckynumbers = ['4', '7']
for i in range(1, 18):
	K = len(luckynumbers)
	for j in range(0, K):
		luckynumbers.append(luckynumbers[j]+'4')
		luckynumbers.append(luckynumbers[j]+'7')
N = int(input())
ans = 'NO'
for i in range(0, len(luckynumbers)):
	if N%int(luckynumbers[i]) == 0:
		ans = 'YES'
		break
print(ans)


k = int(input())
print("codeforces" + "s" * (k - 1))


k = int(input())
s = 'codeforce'
s2 = 's' * k
print(s+s2)


t = int(input())
for _ in range ( t ):
    n = int(input())
    a = 0
    for i in range (1, n+1):
        a *= i
    print(2*a//n//n)


n, k = tuple(map(int, input().split()))
return n * (k // n + 1)


#include<iostream>
using namespace std;
int main(){
    int n,k;
    cin>>n>>k;
    cout<<n+k-n%k;
    return 0;
}


import math
import time
from collections import defaultdict,deque
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
n=int(input())
MOD=1000000007
dp=[[0]*4 for _ in range(n+2)]
dp[0][3]=1
for i in range(1,n+1):
    s=sum(dp[i-1])%MOD
    dp[i][0]=(s-dp[i-1][0])%MOD
    dp[i][1]=(s-dp[i-1][1])%MOD
    dp[i][2]=(s-dp[i-1][2])%MOD
    dp[i][3]=(s-dp[i-1][3])%MOD
print(dp[n][3])


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys, math, random, operator
from string import ascii_lowercase
from string import ascii_uppercase
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
from Queue import Queue, PriorityQueue
from collections import deque, defaultdict, Counter
getcontext().prec = 100

MOD = 10**9 + 7
INF = float("+inf")

if sys.subversion[0] != "CPython":  # PyPy?
    raw_input = lambda: sys.stdin.readline().rstrip()
pr = lambda *args: sys.stdout.write(" ".join(str(x) for x in args) + "\n")
epr = lambda *args: sys.stderr.write(" ".join(str(x) for x in args) + "\n")
die = lambda *args: pr(*args) ^ exit(0)

read_str = raw_input
read_strs = lambda: raw_input().split()
read_int = lambda: int(raw_input())
read_ints = lambda: map(int, raw_input().split())
read_float = lambda: float(raw_input())
read_floats = lambda: map(float, raw_input().split())

"---------------------------------------------------------------"

N = read_int()

num = int(math.sqrt(N))
while num * (num + 1) + 1 > N:
    num -= 1

pos = num * (num + 1) / 2 + 1
val = 1
lim = num + 1
while pos < N:
    pos += 1
    val += 1
    if val > lim:
        val = 1
        lim += 1
print val


n=int(input())
n=n-1
ar=[1]
for i in range(1,n+1):
    j=0
    while(j<i+1):
        ar.append(j+1)
        j+=1
print(ar[n])


a=[int(i) for i in input()]
b=int(input())
res=0
def summ(s,cou):
    global res
    if len(s)<=0:
        if int(cou)>res and int(cou)<=b:
            res=int(cou)
    else:
        for i in range(len(s)):
            summ(s[0:i]+s[i+1:len(s)],cou+str(s[i]))
summ(a,"")
print(res)


s = input()
a = s.split(' ')
m=[]
l=[]
f=[]
for i in a:
    m += i

for i in m:

    if i =='+':
        i=''

    l+=i

def buble_sort(list1):
    amount = len(list1)-1
    for i in range(0,amount):
        for x in range(0,amount):
            if list1[x] > list1[x+1]:
                list1[x],list1[x+1] = list1[x+1],list1[x]
    return list1
new_list = buble_sort(l).copy()

n=0
while n < len(new_list)-1:
    for i in new_list:
        f+=i
        f+='+'
    if len(f) > len(new_list)-1:
        break

    n+=1
del f[-1]
m = ''.join(f)
print(m)


from itertools import permutations

def check(date):
	y,m,d = date

	if (m in [1,3,5,7,8,10,12] and d > 31) or \
		(m in [2,4,6,9,11] and d > 30) or m>12:
		return False
	elif m == 2 and ((not y%4 and d>29) or (y%4 and d>28)):
		return False
	else:
		return True

def date_diff(cdate,bdate):
	if bdate[2]==29 and bdate[1]==2 and not bdate[0]%4:
		bdate = bdate[0]+18,3,1
	else:
		bdate[0]+=18

	if bdate <= cdate:
		return True
	else:
		return False

def main():
	cdate = [int(x) for x in raw_input().split('.')][::-1]
	bdate = [int(x) for x in raw_input().split('.')][::-1]

	possible = 'NO'
	for date in permutations(bdate):
	#	print date,
		date = list(date)

		if check(date):
	#		print 'passed'
			if date_diff(cdate,date):
				possible = "YES"
				break
#		else:
	#		print 'failed'

	print possible
if __name__ == "__main__":
	main()


a,b,c = raw_input().split()
a=int(a)
b=int(b)
ce=int(c)
a=a*(10**100000)
z=a/b
k=[]
l=0
while(z>0):

	k.append(z%10)
	z/=10
	l+=1
l-=1
plus=0
ans=-1
while(plus<80000):
	plus+=1
	if(k[l]==ce):
		ans=plus
		break;
	l-=1

print(ans)


n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 2 or m > 2:
    print("Second")
elif n == 2 and m == 2:
    print("Second")
else:
    print("First")


import sys
range = xrange
input = raw_input

MOD = 10**9+7
def mult(A,B):
    n = len(A)
    C = [[0]*n for _ in range(n)]
    for x in range(n):
        for y in range(n):
            for z in range(n):
                C[x][y] += A[z][y]*B[x][z]
            C[x][y]%=MOD
    return C

def vecmult(A,B):
    n = len(A)
    C = [0]*n
    for y in range(n):
        C[y] = sum(A[x][y]*B[x] for x in range(n))%MOD
    return C

n,m = [int(x) for x in input().split()]

#def DP(n):
#    if n<=0:
#        return 1 if n==0 else 0
#    else:
#        return DP(n-m) + DP(n-1)

mapper = [[0]*m for _ in range(m)]

mapper[0][0] = 1
mapper[-1][0] = 1
for i in range(m-1):
    mapper[i][i+1] = 1

def power(A,B,m):
    n = len(A)
    if m == 0:
        return B
    while m>1:
        if m%2==1:
            B = vecmult(A,B)
        A = mult(A,A)
        m//=2
    return vecmult(A,B)

vec = [1]*m
vec = power(mapper,vec,n)
print(vec[-1]%MOD)


import numpy as np
n=int(input())
li=[]
for i in range(n):
    a=list(map(int,input().split()))
    li.append(a)
li=np.array(li)
for i in range(n):
    for j in range(n):
        if(i==j):
            count+=1
        if(i+j==n):
            count+=1
for j in range(n):
    count+=a[n//2][j]
for i in li[:,n//2]:
    count+=i

count-=3*li[n//2][n//2]


x, y, m = map(int, input().split())
if x < y: x, y = y, x
if x > 0:
    s = 0
    while x < m:
        x, y = x + y, x
        s += 1
elif: x < m: print(-1)
else: print(0)


def gen(a):
    if a==0 or a==1:
        return [a]
    else:
        k = a//2
        t = gen(k)
        return t + [a%2] + t

n, l ,r = map(int, input().split() )

s = gen(n)

count = 0
for num in s[l-1:r]:
    if num == 1:
        count+=1
print(count)


import random, math
from copy import deepcopy as dc

# Function to call the actual solution
def solution(li, i):
	# print(i, li)
	if i >= len(li):
		return li
	if li[i] <= 1:
		return solution(li, i+1)
	l = li[i]//2
	r = li[i] % 2
	# Change
	out = solution([l], 0)
	return out + [r] + out

# Function to take input
def input_test():
	n, l, r = map(int, input().strip().split(" "))
	out = solution([n], 0)
	c = 0
	for i in range(l-1, r):
		if out[i] == 1:
			c += 1
	print(c)

input_test()
# test()


def solve(n,l,m):
    if n==1:
        return [1]
    if n==0:
        return [0]
    else:
        d,m=divmod(n,2)
        a=solve(d,l,m)
        return a+[m]+a
t=1
# t=int(input())
while(t>0):
    n,l,m = [int(x) for x in input().split()]
    arr=solve(n,l,m)
    l-=1
    sum=0
    while(l<m):
        sum+=arr[l]
        l+=1
    print(sum)
    t-=1


#!/usr/bin/env python

import random

def read():
    return input()

def g(n):
    strNum = str(n)

    ret = 0
    for idx in range(len(strNum)):
        digit = int(strNum[idx])

        for i in range(1, 10):
            leftNum     = int(strNum[:idx]    ) if idx > 0 else 0
            rightNum    = int(strNum[idx + 1:]) if idx + 1 < len(strNum) else 0
            rightDigits = len(strNum) - idx - 1

            if i < digit:
                ret += i * (leftNum  + 1) * (10 ** rightDigits)

            elif i > digit:
                ret += i * (leftNum     ) * (10 ** rightDigits)

            elif i == digit:
                ret += i * (leftNum     ) * (10 ** rightDigits)
                ret += i * (rightNum + 1)

    return ret

def work(a):
    mul = 1
    while mul:
        L = 0
        R = mul * a
        while L < R:
            mid = (L + R) / 2

            if g(mid) >= mul * a:
                R = mid
            else:
                L = mid + 1

        if g(L) == mul * a:
            print 1, L
            break

        mul += 1

if __name__ == "__main__":
    work(read())


r = input
ans = n = int(r())
s = r()
len = 1
while len * 2 <= n:
  if s[0:len] == s[len:len*2]:
    ans = min(ans, n - len + 1)
print(ans)


import math
def primes(max_n):
    max_n-=1
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4

    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)
        if initial > half:
            return [2] + filter(None, numbers)
def factors(a):
    j = 0
    p = {}
    while (a > 1):
        b = asd[j]
        if a % b == 0:
            a /= b
            if b not in p:
                p[b] = 1
        else:
            j += 1
    p = p.keys()
    p.sort()
    return p
asd=primes(10**6+1)
check={}
for i in asd:
    check[i]=1
def help(arr,num):
    don=[]
    if num not in check:
        for i in arr:
            p=num/i
            #print p,i
            for j in range(num-i+1,num+1):
                if j not in al:
                    al[j]=1
                    don.append(j)
    return don
#print help(factors(16),16)

n=input()
ans=[]
al={}
f=factors(n)
a=help(f,n)
al={}
for i in a:
    af=help(factors(i),i)
    #print af,i
    ans+=af

print min(ans)


import math
def primes(max_n):
    max_n-=1
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4

    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)
        if initial > half:
            return [2] + filter(None, numbers)
def factors(a):
    j = 0
    p = {}
    while (a > 1):
        b = asd[j]
        if a % b == 0:
            a /= b
            if b not in p:
                p[b] = 1
        else:
            j += 1
    p = p.keys()
    p.sort()
    return p
asd=primes(10**6+1)
check={}
for i in asd:
    check[i]=1
def help(arr,num):
    don=[]
    if num not in check:
        for i in arr:
            p=num/i
            #print p,i
            for j in range(num-i+1,num+1):
                    don.append(j)
    return don
def help2(arr,num):
    don=[]
    if num not in check:
        for i in arr:
            don.append(num-i+1)
    return don

#print help(factors(16),16)

n=input()
ans=[]
f=factors(n)
a=help(f,n)
for i in a:
    af=help(factors(i),i)
    #print af,i
    ans+=af
print min(ans)


import itertools

def countZeroes(s):
    ret = 0
    for i in s:
        if i != '0':
            break
        ret += 1
    return ret

def stupid(n):
    ansMax = 0
    bn1 = n
    bn2 = n
    for n1 in itertools.permutations(n):
        for n2 in itertools.permutations(n):
            val = str(int(''.join(n1)) + int(''.join(n2)))[::-1]
            cnt = countZeroes(val)
            if cnt > ansMax:
                ansMax = cnt
                bn1 = ''.join(n1)
                bn2 = ''.join(n2)
    return (bn1, bn2)

def solution(n):
    ansMax = n.count('0')
    bestN1 = n.replace('0', '') + ansMax * '0'
    bestN2 = n.replace('0', '') + ansMax * '0'

    for i in range(1, 10):
        cnt1 = [n.count(str(j)) for j in range(10)]
        cnt2 = [n.count(str(j)) for j in range(10)]

        if cnt1[i] == 0 or cnt2[10 - i] == 0:
            continue
        cnt1[i] -= 1
        cnt2[10 - i] -= 1
        curN1 = str(i)
        curN2 = str(10 - i)
        ansCur = 1
        for j in range(10):
            addend = min(cnt1[j], cnt2[9 - j])
            ansCur += addend

            cnt1[j] -= addend
            cnt2[9 - j] -= addend

            curN1 += str(j) * addend
            curN2 += str(9 - j) * addend

        if cnt1[0] > 0 and cnt2[0] > 0:
            addend = min(cnt1[0], cnt2[0])
            ansCur += addend

            cnt1[0] -= addend
            cnt2[0] -= addend

            curN1 = '0' * addend + curN1
            curN2 = '0' * addend + curN2

        if ansCur > ansMax:
            ansMax = ansCur
            f = lambda x: str(x[0]) * x[1]
            bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1]
            bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1]

    return (bestN1, bestN2)

for n in range(1, 100500):
    answer = map(int, stupid(str(n)))
    candidate = map(int, solution(str(n)))

    if countZeroes(str(sum(answer))[::-1]) != countZeroes(str(sum(candidate))[::-1]):
        print('Wrong on test', n)
        print('Answer is', stupid(str(n)))
        print('Output is', solution(str(n)))
        break


h, w = map(int, input().split())
go = [[[] for x in range(w)] for y in range(h)]
s = input()
t = input()
c1 = s[0] == '<' and s[w - 1] == '>' and t[0] == 'v' and t[h - 1] == '^'
c2 = s[0] == '>' and s[w - 1] == '<' and t[0] == '^' and t[h - 1] == 'v'
print("YES" if c1 or c2 else "NO")


def smaller( a):
    res = 1
    while res<=a:
        res = res * 2
    return res/2

a=raw_input()
a=a.split()

b = []

for i in range(len(a)):
    b.append(int(a[i]))

if b[0]==b[1]:
    print 0

while b[0]>=smaller(b[1]):
    c = smaller(b[1])
    b[0], b[1] = b[0]-c, b[1]-c

print smaller(b[1])*2-1


n, s = map(int, input().split())
coins = [1e9] * (s+1)
coins[0] = 0
for i in range(1, s+1):
    for j in range(1, n+1):
        if i >= j:
            coins[i] = min(coins[i], coins[i - j] + 1)
        else:
            break
print(coins[s])


s = [[]] * 3
for i in range(3):
    s[i] = raw_input()
f = 0
for i in range(3):
    for j in range(3):
        if(s[i][j] != s[3-i][3-j]):
            f = 1
if(f):
    print "YES"
else:
    print "NO"


a=input()
d=[]
i=0
while i<len(a):
    if a[i+2]!="B":
        while a[i+2]!="B":
            d.append(a[i])
            i=i+1
        d.append(" ")
    else:
        i=i+3
print("".join(d))


mp = lambda: map(int, raw_input().split())
r1, r2 = mp()
c1, c2 = mp()
d1, d2 = mp()
b = -1
f = False
for a in range(1, 10):
    b = r1-a
    c = c1-a
    d = d1-a
    if b < 0 or c < 0 or d < 0 or b > 9 or c > 9 or d > 9:
        continue
    if c + d == r2 and c + b == d2 and b + d == c2 and len(set[a, b, c, d])==1:
        f = True
        break
if not f:
    print -1
else:
    print a, b
    print c, d


import math
cnt=0
st=""
from itertools import combinations
def powerset(string):
    global cnt
    for i in range(0,len(string)+1):
        for element in combinations(string,i):
            if(''.join(element)=="QAQ"):
                cnt+=1
def powerSet(arr, n) :
    global cnt
    global st
    opsize = math.pow(2, n)
    for counter in range( 1, (int)(opsize)) :
        st=""
        for j in range(0, n) :
            if (counter & (1<<j)) :
                st+=arr[j]
                print(st)
                if(st=="QAQ"):
                    cnt+=1
if(__name__=='__main__'):
    s1=input()
    index=0
    curr=""
    powerset(s1)
    print(cnt)


num, index = map(int,raw_input().split())
arr = [1]
if index == 1:
	print arr[index]
else:
	for i in range(2,num+1):
		arr.append(i)
		arr = arr + arr
		arr.pop()
	print arr[index-1]


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

l = [[1]]
for i in range(n-1) :

    temp = l[-1][:]

    temp.append(max(l[-1])+1)

    for i in l[-1] :

        temp.append(i)

    l.append(temp)

print(l[-1][k-1])


b,d=map(int,raw_input().split())
for i in xrange(1,10):
    if (b**i)%d==0:
        print "2-type"
        print i
        exit()
if (b-1)%d==0:
    print "3-type"
elif (b+1)%d==0:
    print "11-type"
elif ((b-1)*b*(b+1))**10 % d == 0:
    print "6-type"
else:
    print "7-type"


import sys

b, d = [int(s) for s in sys.stdin.readline().split(' ')]

def pf(d):
    l = []
    i = 2
    while i * i <= d:
        if d % i == 0:
            while d % i == 0: d /= i
            l.append(i)
    if i > 1:
        l.append(i)
    return l

def typ(b, d):
    if (b ** 7) % d == 0:
        i, bb = 1, b
        while bb % d != 0:
            i, bb = i + 1, bb * b
        return (2, i)
    elif (b - 1) % d == 0:
        return 3
    elif (b + 1) % d == 0:
        return 11
    else:
        p = pf(d)
        if p and all(typ(b, f)[0] != 7 for f in p):
            return 6
        else:
            return 7

t=typ(b,d)
if isinstance(t, int):
    print "%d-type" % t
else:
    print "%d-type" % t[0]
    print t[1]


t=input()
for i in range(len(t)-1):
    if t[i]==t[i+1]
    del(t[i])

if len(t)%2==0:
    print('CHAT WITH HER')
elif len(t)%2==1:
    print('IGNORE HIM')


n=int(input())
m=[int(x) for x in input().split()]
m.sort()
y=" ".join(m)
print(y)


# -*- coding: utf-8 -*-
#ᕕ┌◕ᗜ◕┐ᕗ HELLO HELLO HELLO ᕕ┌◕ᗜ◕┐ᕗ

n = int(raw_input())
s = raw_input()
"jolt"
"flar"
"umbr"
"leaf"
"glac"
"sylv"
if n == 6:
    print "espeon"
if n == 8:
    print "vaporeon"
if n == 7:
    if s[0] == 'j' or s[1] == 'o' or s[3] == 't':
        print "jolteon"
    if s[0] == 'f':
        print "flareon"
    if s[0] == 'u' or s[1] == 'm' or s[2] == 'b':
        print "umbreon"
    if s[0] == 'l' or s[1] == 'e' or s[3] == 'f':
        print "leafeon"
    if s[0] == 'g' or s[3] == 'c':
        print "glaceon"
    if s[0] == 's' or s[1] == 'y' or s[3] == 'v':
        print "sylveon"
    if s[1] == 'l':
        if s[3] == 'r':
            print "flareon"


table = ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
n = int(raw_input())
s = raw_input()

res = ""
for na in table:
	for i in range(n):
		if s[i] != '.' and s[i] != na[i]:
			break
	else:
		res = na
		break

print res


nums = [int(r) for r in input().split()]
val = nums[1]*nums[3]*nums[5]/(nums[0]*nums[2]*nums[4])
if val > 1:
    print("Ron")
else:
    print("Hermione")


s = raw_input()
k = int(raw_input())
k1 = ''
for i in xrange(k):
    k1 += '1'
s = s + k1

def sravn(s):
    for i in xrange(len(s)/2):
        if s[i] != s[i+len(s)/2] and s[i+len(s)/2] != '1':
            return 'no'
    print len(s-1)
    return 'yes'

l = len(s)/2*2-1
while l >= 1:
    for i in xrange(len(s)-l+1):
        t = sravn(s[i:i+l+1])
        if t == 'yes':
            l = -1
            break
    l -= 2


line = input().strip();
a = line.split(" ")[0];
b = line.split(" ")[1];
s = a + b;
m = 0;
for c in s :
    d = int(c);
    m = max(m, d);

t = int(a) + int(b)
ret = "";
while (t != 0):
    r = t % (m + 1);
    t //= (m + 1);
    ret = ret + str(r);
print(len(ret));


# -*- coding: utf-8 -*-
"""
Created on Mon May 25 14:38:46 2020

@author: Ritvik Agarwal
"""
n, wps = input(), map(int, raw_input().split())
i, summ = 0, 0
while summ < n:
    if i == 7:
        i = 1
    else:
        i += 1
    summ += wps[i-1]
print i


#!/usr/bin/env python

import sys
import logging
import traceback

logging.basicConfig(level = logging.INFO)

s = raw_input()

indice = [[] for i in range(26)]

for i in range(len(s)) :
	indice[ord(s[i])-ord('A')] += [i]

maxCnt = -1
for l in indice :
	if len(l) == 0 :
		continue
	s = 0
	c = 0
	cnt = 1
	while True :
		if c >= len(l) :
			break
		if (l[c] - l[s]) % 2 == 1 :
			cnt += 1
			s = c
			c += 1
		else :
			c += 1
	if cnt > maxCnt :
		maxCnt = cnt

print maxCnt


count=sum1=sum2=0
count1=0
count2=0
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
for i in range(n):
	if a[i]>b[i]:
		count+=1
	elif a[i]<b[i]:
		count1+=1
	else:
		count2+=1

if count2==n or count1==n and count==0:
	print("-1")
elif count1==0 or count==0:
	print("1")
else:
	if count==1:
		sum1=count1+count
		print(sum1)
	elif count1!=0:
		final=count1/count+1
		print(int(final))
	else
		print("-1")


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

if int((n-1)/k)*t > d:
    print('YES')
else:
    print('NO")


n = int(input())
tab = []
for i in range(1 , n + 1):
    tab.append(i)
for i in range(0 , len(tab) , 2):
    tab[i] = tab[i] * -1
print(sum(tab))


while(1 > 0):
    num1 = str(input('enter the numbre component of 0 and(or) 1 :'))
    num2 = str(input('enter the numbre component of 0 and(or) 1 :'))
    if len(num1)==len(num2):
        if '2' not in num1 and '3' not in num1 and '4' not in num1 and '5' not in num1 and '6' not in num1 and '7' not in num1 and '8' not in num1 and '9' not in num1:
            if  '2' not in num2 and '3' not in num2 and '4' not in num2 or '5' not in num2 and '6' not in num2 and '7' not in num2 and '8' not in num2 and '9' not in num2:
                if len(num1)>=0 and len(num1)<=100:
                    if len(num2)>=0 and len(num2)<=100:
                        for i in range(len(num1)):
                            if num1[i]==num2[i]:
                                print('0', end='')
                            else:
                                print('1', end='')
                        print('')
                    else:
                        print('The num2 must be 0 or less or equal to 100')
                else:
                    print('The num1 must be 0 or less or equal to 100')
            else:
                print('num2 must contain only the numbers 0 and or 1')
        else:
            print('num1 must contain only the numbers 0 and or 1')
    else:
        print('Please enter the same length for num1 and num2')


a = 0
for i in s:
    if i == 'a':
		a+=1
half = len(s)//2
if a > half:
	print(a)
else:
	alls = len(s)
	while a <= half:
		alls-=1
		half = alls//2
	print(alls)


s = input()
print(min(s.count('a')*2-1, len(s))


n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[]
for i in range(m):
    for j in range(b[i]):
        c.append(i+1)
flag=1
for i in range(n-m+1):
    temp=a[i:i+m+1]
    if(sorted(temp)==sorted(c)):
        print("YES")
        flag=0
        break
if flag:
    print("NO")


def main():
  path = input()
  coordinate = [[0 for i in range(2)] for j in range(len(path)+1)]
  coordinate[0] = [0,0]
  left = 0
  right = 0
  up = 0
  down = 0

  for direction in path:
    if direction == 'U':
      up += 1
    elif direction == 'R':
     right += 1
    elif direction == 'D':
      down += 1
    elif direction == 'L':
      left += 1

  if (left = 1 and right = 1 and up = 1 and down = 0) or (left = 1 and right = 1 and up = 0 and down = 1) or (left = 1 and right = 0 and up = 1 and down = 1) or (left = 0 and right = 1 and up = 1 and down = 1):
      print('BUG')
      return

  for i in range(0,len(path)):
    if i == 0:
      if path[i] == 'U':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = 1
      elif path[i] == 'R':
        coordinate[i + 1][0] = 1
        coordinate[i + 1][1] = 0
      elif path[i] == 'D':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = -1
      elif path[i] == 'L':
        coordinate[i + 1][0] = -1
        coordinate[i + 1][1] = 0
    else:
      if path[i] == 'U':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += 1 + coordinate[i][1]
      elif path[i] == 'R':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += 1 + coordinate[i][0]
      elif path[i] == 'D':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += -1 + coordinate[i][1]
      elif path[i] == 'L':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += -1 + coordinate[i][0]
  coordinateSet = list(set(map(tuple,coordinate)))
  if len(coordinate) == len(coordinateSet):
    print('OK')
  else:
    print('BUG')

main()


def main():
  path = input()
  coordinate = [[0 for i in range(2)] for j in range(len(path)+1)]
  coordinate[0] = [0,0]
  left = 0
  right = 0
  up = 0
  down = 0

  for direction in path:
    if direction == 'U':
      up += 1
    elif direction == 'R':
     right += 1
    elif direction == 'D':
      down += 1
    elif direction == 'L':
      left += 1
  allDirections = [left,up,down,right]
  minDirection = min(allDirections)
  if minDirection == 0:
    allDirections.remove(0)
    minDirection = min(allDirections)
  i = minDirection + 1
  repeatingSequences = []
  while i < len(path):
    currentSet = set(path[i-minDirection - 1:i])
    if len(currentSet) == 1:
      repeatingSequences.append(path[i])
      i += minDirection
    else:
      i += 1
  if len(set(repeatingSequences)) == 3:
      print('BUG')
      return

  for i in range(2,len(path)):
    if path[i] != path[i-1] and path[i] != path[i-2] and path[i-1] != path[i-2]:
      print('BUG')
      return

  for i in range(0,len(path)):
    if i == 0:
      if path[i] == 'U':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = 1
      elif path[i] == 'R':
        coordinate[i + 1][0] = 1
        coordinate[i + 1][1] = 0
      elif path[i] == 'D':
        coordinate[i + 1][0] = 0
        coordinate[i + 1][1] = -1
      elif path[i] == 'L':
        coordinate[i + 1][0] = -1
        coordinate[i + 1][1] = 0
    else:
      if path[i] == 'U':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += 1 + coordinate[i][1]
      elif path[i] == 'R':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += 1 + coordinate[i][0]
      elif path[i] == 'D':
        coordinate[i + 1][0] = coordinate[i][0]
        coordinate[i + 1][1] += -1 + coordinate[i][1]
      elif path[i] == 'L':
        coordinate[i + 1][1] = coordinate[i][1]
        coordinate[i + 1][0] += -1 + coordinate[i][0]
  coordinateSet = list(set(map(tuple,coordinate)))

  if len(coordinate) == len(coordinateSet):
    print('OK')
  else:
    print('BUG')

main()


def move(s, i):
		if s[i] == 'U':
			return 0, 1;
		elif s[i] == 'D':
			return 0, -1;
		elif s[i] == 'L':
			return -1, 0;
		else:
			return 1, 0;
a, b = map(long, raw_input().split());
s = raw_input();
l = len(s);
x, y = [0]*(l+1), [0]*(l+1)
f = 0;
for i in xrange(1, l+1):
	x[i], y[i] = x[i-1], y[i-1];
	tmpx, tmpy = move(s, i-1)
	x[i] += tmpx;
	y[i] += tmpy;
if a == 0 and b == 0:
	print "Yes";
else:
	for i in xrange(1, l+1):
		if x[l] == 0 and y[l] != 0:
			if a == x[i] and (b - y[i]) % y[l] == 0:
				f = 1
				break;
		elif y[l] == 0 and x[l] != 0:
			if b == y[i] and (a - x[i]) % x[l] == 0:
				f = 1
				break;
		elif x[l] == 0 and y[l] == 0:
			if a == x[i] and b == y[i]:
				f = 1;
				break;
		elif (a - x[i]) % x[l] == 0 and (b - y[i]) % y[l] == 0:
			if (a - x[i]) / x[l] == (b - y[i]) / y[l] and (b - y[i]) / y[l] >= 0:
				f = 1;
				break;

	if f:
		print "Yes";
	else:
		print "No";


l1=['ten'  ,'eleven', 'twelve' ,'thirteen' ,'fourteen','fifteen','sixteen' ,'seventeen','eighteen','nineteen']
l2=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
l3=['','one','two','three','four','five','six','seven','eight','nine']
for i in range(100):
n = input()
if n=='0' : print('zero')
elif 10<=int(n)<=19:
    print(l1[int(n)-10])
else:
    if len(n)==1 : print(l3[int(n)])

    else :
        if n[1]=='0':print(l2[int(n[0])])
        else : print(l2[int(n[0])] + '-' + l3[int(n[1])])


a = ["","one","two","three","four","five","six","seven","eight","nine"]
b = ["","","twen","thir","for","fif"]
c = ["","-one","-two","-three","-four","-five","-six","-seven","-eight","-nine"]
n = int(input())

if n<10:
    print (a[n])
elif n == 11:
    print ("eleven")
elif n == 12:
    print ("twelve")
elif n == 10:
    print ("ten")
elif n == 14:
    print ("fourteen")
elif n == 18:
    print ("eighteen")

elif n//10 == 1:
    if n<16:
        print (str(b[n-10])+"teen")
    else:
        print (str(a[n-10])+"teen")
elif n//10<6:
    print (str(b[n//10]+"ty"+str(c[n%10])))
else:
    if n//10 !=  8:
        print (str(a[n//10]+"ty"+str(c[n%10])))
    else:
        print ("eight"+str(c[n%10])
if n == 0:
    print ("zero")


data = [int(info) for info in input().split(' ')]

info = set(range(data[0], data[1] + 1)).intersection(set(range(data[2], data[3] + 1)))

if data[4] in info:
	print(len(info) - 1)
else:
	print(len(info))


inp=input().split()

c1=int(inp[0])
r1=int(inp[1])
c2=int(inp[2])
r2=int(inp[3])

print((r1+r2)*2+8)


"""
instagram : essipoortahmasb2018
telegram channel : essi_python

"""
i = input
List = [*map(int,i().split())]
#w1 h1 w2 h2
#2  2  1  2

#Result = List[1]+List[3]+4
#2 1 2 1
h = List[1]*2
w = List[0]
Result =  ((h + 2)*2)+(w*2)
print(Result)


from sys import stdin
print(6-len(stdin.readline())


import sys

def read():
    global gl, gr, bl, br

    girl = input.readline()
    gl = int(girl.split(' ')[0])
    gr = int(girl.split(' ')[1])

    boy = input.readline()
    bl = int(boy.split(' ')[0])
    br = int(boy.split(' ')[1])

def check_possible(g, b):

    if g == b:
        return True

    elif g > b:

        if b == g - 1:
            return True
        else:
            return False

    elif g < b:

        if b <= 2*g + 2:
            return True
        else:
            return False

def main():

    poss = check_possible(gl, br)
    if poss:
        output.write('YES')
        return

    poss = check_possible(gr, bl)
    if poss:
        output.write( 'YES')
        return

    otput.write('NO')

def run():

    global input, output
    input = sys.stdin
    output = sys.stdout

    read()
    main()

if __name__ == '__main__':
    run()


ar, al = map(int, input().split())
br, bl = map(int, input().split())
print('YES' if 2 * (ar + 1) >= bl >= ar - 1 or 2 * (al + 1) >= br >= al - 1] else 'NO')


import bisect
a,b,c=map(int,input().split(' '))
times=[]
for i in range(10**8):
    times.append(b*(i+1))
pos=bisect.bisect_left(times,(a-b)*c,0,len(times))
print(times)
print(pos+1)


m,n=raw_input().split()
h=1
g=1
m=int(m)
n=int(n)
for i in range(n):
    h=long(h*m)
for i in range(m):
    g=long(g*n)
if h>g:
    print ">"
elif h<g:
    print "<"
else:
    print "="


from sys import *
from heapq import *
from collections import defaultdict
from itertools import permutations
import os, sys
from io import IOBase, BytesIO
M=10**9+7
def graph_as_tree_1_root():
    n=int(input())
    dict=defaultdict(list)
    for _ in range(n-1):
        x,y=list(map(int,input().split()))
        dict[x].append(y)
        dict[y].append(x)
    tree=[[1]]
    temp=[1]
    vall=0
    seen=set([i for i in range(2,n+1)])
    lol=[]
    while len(seen)>0:
        #print(seen)
        lol=list(seen)
        tt=[]
        for x in temp:
            aa=[]
            for val in dict[x]:
                if val in seen:
                    aa+=[val]
                    seen.remove(val)
            dict[x]=aa
            tt+=aa
        tree.append(tt)
        temp=tt
        vall+=1
    for x in lol:
        dict[x]=[]

    print(tree,dict)
def pow(a,b):
    res=1
    while b>0:
        if b&1:
            res*=a
        a*=a
        b>>=1
    return res
def powmod(a,b,m):
    res=1
    while b>0:
        if b&1:
            res=((res*a)%m)
        a*=a
        b>>=1
    return res
def inv(a,m):
    return powmod(a,m-2,m)
def alldivisors(n) :
    list = []
    arr=[]
    for i in range(1, int(sqrt(n) + 1)) :
        if (n % i == 0) :
            if (n / i == i) :
                arr+=[i]
            else :
                arr+=[i]
                list.append(n//i)
    arr+=list[::-1]
    return arr
def primefactorisation(n):
    potentional_p = 3
    itog_list = defaultdict(int)
    if n % 2 == 0:
        itog_list[2] = 0
    while n % 2 == 0:
        n = n // 2
        itog_list[2] += 1
    while n - 1:
        if potentional_p > (n**0.5):
            itog_list[n] += 1
            return itog_list
        while n % potentional_p == 0:
            n = n // potentional_p
            itog_list[potentional_p] += 1
        potentional_p += 2
    return itog_list

def main():
    n,m=list(map(int,input().split()))
    val=((1<<m)-1)%M

    val=powmod(val,n,M)
    print(val)

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.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')

if __name__ == '__main__':
    main()
#threading.Thread(target=main).start()


import sys
from math import ceil

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

if n == 1:
    print m
elif m == 1:
    print n
elif (n * m) % 2 == 0:
    print (n*m)/2
else:
    print (n*m)/2+1


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

left4seat = n
left2seat = n * 2
left1seat = 0
for i in range (0, n) :
	left4seat -= a[i] // 4
	if (left4seat < 0) :
		left2seat += 2 * left4seat
		left4seat = 0

index = 0
while (index < k ) :
	leftSol = a[index] % 4
	if (leftSol >= 3) :
		if (left4seat > 0) : left4seat -= 1
		else : left2seat -= 2
	elif (leftSol == 2) :
		if (left4seat > 0) :
			left4seat -= 1
			left1seat += 1
		else :
			left2seat -= 1
	elif (leftSol == 1) :
		if (left1seat > 0) : left1seat -= 1
		elif (left4seat > 0) :
			left4seat -= 1
			left2seat += 1
		else :
			left2seat -= 1
	if (left4seat < 0 or left2seat < 0) : break
	index += 1

if (index == k and left4seat >= 0 and left2seat >= 0) : print("YES")
else : print("NO")


#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from collections import deque
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

def process(grid, a, n, m):
    aux = [[0] * 3000 for _ in range(3000)]
    for i in range(n):
        mi = deque()
        for j in range(a):
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])

        aux[0][i] = mi[0]
        for j in range(a, m):
            if mi[0] == grid[i][j - a]:
                mi.popleft()
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])
            aux[j - a + 1][i] = mi[0]

    return aux

def main():
    n, m, a, b = map(int, input().split())
    g, x, y, z = map(int, input().split())

    grid = [[0] * 3000 for _ in range(3000)]
    for i in range(n):
        for j in range(m):
            grid[i][j] = g
            g = (g * x + y) % z

    aux1 = process(grid, b, n, m)
    aux2 = process(aux1, a, m - b + 1, n)

    print(sum(sum(aux2[i][:m - b + 1]) for i in range(n - a + 1)))

# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

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

class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from collections import deque
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

def process(grid, a, n, m):
    aux = [[0] * 3000 for _ in range(3000)]
    for i in range(n):
        mi = deque()
        for j in range(a):
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])

        aux[0][i] = mi[0]
        for j in range(a, m):
            if mi[0] == grid[i][j - a]:
                mi.popleft()
            while mi and grid[i][j] < mi[-1]:
                mi.pop()
            mi.append(grid[i][j])
            aux[j - a + 1][i] = mi[0]

    return aux

def main():
    n, m, a, b = map(int, input().split())
    g, x, y, z = map(float, input().split())

    MOD = int(z)
    MODF = z
    MAGIC = 6755399441055744.0
    SHRT = 65536.0

    MODF_INV = 1.0 / MODF
    SHRT_INV = 1.0 / SHRT

    fround = lambda x: (x + MAGIC) - MAGIC
    fmod = lambda a: a - MODF * fround(MODF_INV * a)
    fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)

    grid = [[0.0] * 3000 for _ in range(3000)]
    for i in range(n):
        for j in range(m):
            grid[i][j] = int(g) % MOD
            g = fmul(g, x, y)

    aux1 = process(grid, b, n, m)
    aux2 = process(aux1, a, m - b + 1, n)

    ans = 0
    for i in range(n - a + 1):
        ans += sum(aux2[i][:m - b + 1])

    print(ans)

# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

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

class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


from __future__ import division, print_function
def main():
    from collections import deque

    def printMin(arr, n, k):
        res=[]
        Qi = deque()
        for i in range(k):
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i);

        for i in range(k, n):
            res.append(arr[Qi[0]])
            while Qi and Qi[0] <= i-k:
                Qi.popleft()
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i)
        res.append(int(arr[Qi[0]]))
        return res
    n,m,a,b=map(int,input().split())
    g,x,y,z=map(int,input().split())

    grid= [0]*(n*m)
    grid[0]=g
    for i in range(1,n*m):
        grid[i]=(grid[i-1]*x+y)%z
    B=[]
    ans=0
    for i in range(n):
        B.append(printMin(grid[i*m:(i+1)*m],m,b))
    grid=[]
    for i in range(len(B[0])):
        temp=[]
        for j in range(n):
            temp.append(B[j][i])
        ans+=sum(printMin(temp,len(temp),a))
    print(ans)
######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()


from __future__ import division, print_function
def main():
    from collections import deque

    def printMin(arr, n, k):
        res=[]
        Qi = deque()
        for i in range(k):
            while Qi and arr[i] <= arr[Qi[-1]] :
                Qi.pop()
            Qi.append(i);

        for i in range(k, n):
            res.append(arr[Qi[0]])
            while Qi and Qi[0] <= i-k:
                Qi.popleft()
            while Qi and arr[i] <= arr[Qi[-1]] :
                    Qi.pop()
            Qi.append(i)
        res.append(int(arr[Qi[0]]))
        return res
    n,m,a,b=map(int,input().split())
    g,x,y,z=map(int,input().split())
    grid=[0]
    grid[0]=g
    B=[]
    for i in range(1,n*m):
        if i%m==0:
            B.append(printMin(grid,m,b))
            g=grid[-1]
            grid=[]
            grid.append((g*x+y)%z)
        else :
            grid.append((grid[-1]*x+y)%z)
    B.append(printMin(grid,m,b))
    ans=0
    for i in range(len(B[0])):
        temp=[]
        for j in range(n):
            temp.append(B[j][i])
        ans+=sum(printMin(temp,len(temp),a))
    print(ans)

######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()


def a964(n):
    variations = list()
    for i in range(1, int(n/2)+1):
        variation = list()
        a = int(n/i)
        variation.append(list((a,))*i)
        if a * i != n:
            variation.append(n - a*i)
        variations.append(variation)
    return len(variations) + 1

if __name__ == '__main__':
    n = int(input())
    print(a964(n))


s =raw_input()

def ct(s):
    lx=["Danil", "Olya", "Slava", "Ann", "Nikita"]
    ct=0
    for x in lx:
        if x in s:
            ct+=1
            if ct>=2:
                return "NO"
    if ct==0:
        return "NO"
    elif ct==1:
        return "YES"

print ct(s)


Copy
n,k = input().split()
n = int(n)
k = int(k)
temp = 1

def lcm(x, y):
	if x>y:
		greater = x
	else:
		greater = y
	while True:
		if((greater%x==0)and(greater%y==0)):
			lcm = greater
			break
		greater+=1
	return lcm

def gcd(x,y):
	if x<y:
		temp = x
		x = y
		y = temp
	while(y):
		x, y = y,x%y
	return x

if k == 0:
	print (n)
else:
	while k>0:
		temp=temp*10
		k=k-1
	x = gcd(temp,n)
	temp = int((temp * n)/x)
	print (temp)


n = int(input())
res = [i for i in range(2,n+1,2)]
res1 = [ i for i in range(1,n+1,2)]
result = sum(res) - sum(res1)

print(result)


n = int(input())
a = [str(i * [1, -1][i % 2]) for i in range(1, n+1)]
print(eval('+'.join(a)))


# -*- coding: utf-8 -*-
additions = []
n = int(input())
for i in range(1, n + 1):
    if i % 2 == 0:
        additions.append(i)
    else:
        additions.append(-i)
    if i == n:
        break
print(sum(additions))


a,m=map(int,input().split())
ans="No"
    if a%m==0:
        ans="Yes"
        break
    else:
        a+=a%m
print(ans)


def main():
	n=int(input())
    sum=0
    for i in range(2,(n-1)):
        s=n
        while(s>0):
            sum=sum+(s%i)
            s=s/i
    b=n-2
    a=sum
    #For HCF
    if a<b:
        x=a
        a=b
        b=x
    while (a%b!=0):
        d=a%b
        b=a
        a=d
    hcf=b
    d1=sum/hcf
    d2=(n-2)/hcf
    print("%d/%d",d1,d2)


input()
a=[0]+[*map(int,input().split())]+[1001]
m=c=0
for x,y in zip(a,a[1:])
 if x+1==y:c+=1;m=max(m,c-1)
 else:c=0
print(m)


#map(int,raw_input().split())
import itertools
n = int(raw_input())

def f(x):
    ans = 1
    for i in x: ans *=i
    return ans

p = [2,3,5,7]
ans = 0
for i in xrange(1,n+1):
    for t in itertools.combinations(p,i):
        if (i%2 == 1): ans += (n/f(t))
        else: ans -= (n/f(t))

print n - ans


#include <bits/stdc++.h>
#define TARUNNO ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;
   #define INF 1000000000+7
   #define MAX 100000
   #define pb push_back
   #define pf push_front
   #define pob pop_back
   #define pof pop_front
   #define ins insert
   #define mp make_pair
   #define F first
   #define S second
   #define Endl endl
   #define PII pair<ll,ll>
   #define pii pair<int, int>
   #define PIPII pair<ll , pair<ll, ll> >
#define testing() {cout<<"OK"<<endl;}
#define array(a,n) for(int i=0;i<int(n);i++){cout<<a[i];}
#define vector(v) for(int i=0;i<v.size();i++){cout<<v[i]<<" ";}cout<<endl;
using namespace std;
template<typename T>
string to_string(T str){stringstream stream;stream << str;return stream.str();}

int main(){
TARUNNO;

    return 0;
}

                             //   C O M F O R T A B L Y   N U M B   //


def main():
    n, p = map(int, input().split())
    l = [p, p] + [ord(c) - 97 for c in input()]
    a = l[-2]
    for i in range(n + 1, 1, -1):
        a, b = l[i - 2], a
        for x in range(l[i] + 1, p):
            if a != x != b:
                l[i] = x
                break
        else:
            continue
        break
    else:
        print("NO")
        return
    a, b = l[i - 1], x
    for i in range(i + 1, n + 2):
        for x in range(p):
            if a != x != b:
                l[i] = x
                a, b = b, x
                break
    print("".join(chr(x + 97) for x in l[2:]))

if __name__ == '__main__':
    main()


n = int(input())
x=0
while n>=1:
    if n%2==1:
        x+=1
        n-=1
    else:
        n//=2;
    }
    print(x)


a = int(input())     #no of a's
b = int(input())     #no of b's
c = int(input())     #no of ab's
d = 0

def longest_str(a, b, c):
   if a == b:
      return (c * 2) + a + b
   elif a < b:
      return (c * 2) + a + (a + 1)
   elif a > b:
      return (c * 2) + b + b + 1
   else:
      return "error"

print(longest_str(a, b, c))


a=int(input())
b=int(input())
c=0
while(a!=b):
    if a>b:
        a=a-1
        b=b+1
    else:
        a=a+1
        b=b-1
    c=c+2
print(c)


a = []
for i in range(4):
    c = input()
    a.append((len(c) - 2, c[0]))
a.sort()
gs = a[0][0] * 2 <= a[1][0]
gl = a[3][0] >= a[2][0] * 2
if (gs and gl) or (not gs and not gl):
    print('C')
else:
    print(a[0][1] if


from collections import deque, defaultdict

def solve(n, m):
	q = deque([])
	q.append(n)
	seen = defaultdict(lambda : False)
	seen[n] = True
	steps = 0
	while(not seen[m]):
		size = len(q)
		steps += 1
		for i in range(size):
			val = q.popleft()
			n1 = val * 2
			n2 = val - 1
			if(not seen[n1] and n1 > 0):
				q.append(n1)
				seen[n1] = True
				if(n1 == m):
					break
			if(not seen[n2] and n2 > 0):
				q.append(n2)
				seen[n2] = True
				if(n2 == m):
					break
	return steps

m,n = map(int, raw_input().split())
print solve(m, n)


a,b,c = map(int,input().split())
print((a*c + b -1)//(b-c))


a=input().split()
a=int(a)
n=a[0]
m=a[1]
k=a[2]
if n<=m and n<=k:
	print("Yes")
else:
	print("No")


from itertools import chain, combinations
from collections import defaultdict
import math

def powerset(iterable):
    xs = list(iterable)
    return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))

def has(s):
	h = 1
	p = [2,3,5,7,11,13,17,19,23,29]
	for i in s:
		h *= p[i-1]
	return h

h = set()
total = 0
ok = [int(i) for i in "1000000000000000000"]
require = set(ok)

for s in powerset(ok):
	if has(s) in h or len(s) == 0:
		continue

	h.add(has(s))

	d = defaultdict(int)
	for c in s:
		d[c] += 1

	flag = False
	for i in require:
		if d[i] == 0:
			flag = True
			break
	if flag: continue

	prod = 1
	for k in d:
		prod *= math.factorial(d[k])

	n = len(s)
	total += (n-d[0])*math.factorial(n-1)/prod

print(int(total))


n = list(map(int, input()))
dp = [[1] * 10]
for i in range(1, len(n)):
    dp.append([0] * 10)
    for j in range(10):
        x = j + n[i]
        dp[i][x // 2] += dp[i - 1][j]
        if x % 2:
            dp[i][x // 2 + 1] += dp[i - 1][j]
print(sum(dp[-1]))


#!/usr/bin/python
import sys

def f(x, s, index, length):
	a = int(s[index])
	if index == length - 1:
		return 2 if (a + x) % 2 == 1 else 1
	if (a + x) % 2 == 0:
		return f( (a+x)/2, s, index+1, length)
	else:
		return f( (a+x)//2, s, index+1, length) + \
			   f( (a+x)//2+1, s, index+1, length)

def selfInclude(s):
	for i in range(0, len(s)-1):
		a = int(s[i])
		b = int(s[i+1])
		if abs(a-b) > 1:
			return False
	return True

s = sys.stdin.readline().strip()
result = 0
for i in range(10):
	result += f(i, s, 1, len(s))
print result-1 if selfInclude(s) else result


import os,sys

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
input = lambda: sys.stdin.readline().rstrip("\r\n")

def main():
	n=int(input())
	li=list(map(int,input().split()))

	li.sort()
	li[0],li[n-1]=li[n-1],li[0]
	print(*li)

if __name__ == "__main__":
    read()
    main()


if __name__=='__main__':
    inp = input()
    inp = input()
    arr = inp.split(" ")
    Li = []
    Ls = []
    for a in arr:
        Li.append(int(a))

    Li.sort()
    fst = Li.pop(0)
    lst = Li.pop(-1)
    ans = str(lst)
    for x in Li:
        Ls.append(str(x))
    Ls.sort()
    for s in Ls:
        ans+=" "+s
    ans+=" "+str(f)
    print(ans)


a,b=map(int,input().split())
if not a:
 if not b:print(0,0)
 else:print('Impossible')
else:
    if a>=b:
        t = a
    elif b>a and b=<2*a:
        t = a
    elif b>a and b>2*a:
        t = a + b-2*a

    print(max(t,a+b-bool(b))


import itertools
n, k = list(map(int, input().split()))
arr = []
cr = 1
for i in range(n):
    arr.append(cr)
    cr += 1
pr = list(itertools.permutations(arr, n))
mc = n - k
ac = 0
for i in pr:
    c = 0
    for j in range(n):
        if i[j] == j + 1:
            c += 1
    if c >= mc:
        ac += 1
print(ac)


n=['January', 'February', 'March', 'April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December']
x=input();ans=0
if x=='January':
    ans=0
elif x=='February':
    ans=1
elif x=='March':
    ans=1
elif x=='February':
    ans=1
elif x=='February':
    ans=1
elif x=='February':
    ans=1
elif x=='February':
    ans=1
elif x=='February':
    ans=
s=int(input())


#!/usr/bin/python

from collections import deque
from collections import Counter

def ir():
    return int(raw_input())

def ia():
    line = raw_input()
    line = line.split()
    return map(int, line)

n, k = ia()
while k > 0 and add > 0:
    ans += add
    add -= 4
    k -= 1

print ans


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
#from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#def print(x): return sys.stdout.write(str(x)+'\n')
#sys.setrecursionlimit(100000)
mod=int(1e9+7)

n,m=mdata()
dp=[[2,0,0]]
for i in range(1,m):
    dp.append([2*dp[i-1][0]-dp[i-1][2],dp[i-1][1]+dp[i-1][0]-dp[i-1][2],dp[i-1][0]-dp[i-1][2]])
cnt=dp[-1][1]
k1=dp[-1][0]-dp[-1][1]
k2=0
for i in range(1,n):
    k1,k2=(2*k1-k2+mod)%mod,(k1-k2+mod)%mod
print(cnt+k1)


import itertools

a = raw_input()
b = raw_input()

a = list(a)
b = int(b)

p_list = list(itertools.permutations(a,len(a)))
#p_list = [[int(x) for x in y] for y in p_list]

ans = 0
a_ans = ''
for i in p_list:
    tsum = ''
    for j in range(len(a)):
        tsum += i[j]
    if int(tsum) <= b and int(tsum) > ans:
        ans = int(tsum)
        a_ans = tsum

print a_ans


def normalize(seg):
    if seg[0] != seg[2] and seg[1] != seg[3]:
        return None

    xs = (seg[0], seg[2])
    ys = (seg[1], seg[3])

    return (min(xs), min(ys), max(xs), max(ys))

def valid(shifted):
    w, h = None, None
    for _, _, x, y in shifted:
        if x != 0 and y != 0:
            if w is not None and (w, h) != (x, y):
                return False

            w, h = x, y

    if w is None or h is None:
        return False

    expected = [(0, 0, 0, h), (0, 0, w, 0), (0, h, w, h), (w, 0, w, h)]

    return set(shifted) == set(expected)

def sub(a, x, y):
    return (a[0] - x, a[1] - y, a[2] - x, a[3] - y)

def main():
    segs = [normalize(tuple(map(int, input().split()))) for _ in range(4)]
    poss = False
    for seg in segs:
        shifted = [sub(s, seg[0], seg[1]) for s in segs]
        poss |= valid(shifted)

    print('YES' if poss else 'NO')

main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
# import numpy as np
starttime = time.time()
# import numpy as np
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]

try:
    # sys.setrecursionlimit(int(pow(10,6)))
    sys.stdin = open("input.txt", "r")
    # sys.stdout = open("../output.txt", "w")
except:
    pass

n=L()[0]
A=[1]
i=0
while(A[-1]<=n):
    A.append(A[i]*10+0)
    A.append(A[i]*10+1)
while(A[-1]>n):
    del(A[-1])
print(len(A))

endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")


n=int(input())
q=int(input())
z=pow(2,n+q)
x=z%998244335
print(x)


n,k = map(int,raw_input().split())
i=2
s=[1]
while(i!=n+2):
    if(i==n+1):
        print s[k-1]
        break
    else:
        s.extend(s)
        s.insert(len(s)/2,i)
    i += 1


from sys import stdin, gettrace

if gettrace():
    inputi = input
else:
    def input():
        return next(stdin)[:-1]

    def inputi():
        return stdin.buffer.readline()

def tide(k, t):
    t = t%(2*k)
    if t <= k:
        return t
    else:
        return 2*k - t

def solve():
    n,k,l = map(int, inputi().split())
    dd = [int(a) for a in inputi().split()]
    if max(dd) > l:
        print("No")
        return
    t = 0
    def can_finish(t,i):
        if i == n:
            return True
        for t1 in range(t+1, t+2*k):
            if dd[i] + tide(k,t1) > l:
                return False
            else:
                if can_finish(t1, i+1):
                    return True
        return False
    for i in range(2*k):
        if can_finish(i,0):
            print("Yes")
            return
    else:
        print("No")

def main():
    t = int(inputi())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


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

n, k = (int(x) for x in input().split())
nk = n*k
a, b = (int(x) for x in input().split())
flag1 = [1, 1, -1, -1]
flag2 = [1, -1, 1, -1]
min_ans, max_ans = float('inf'), -1
for s in range(1, k+1):
    for dir in range(4):
        if (s + flag1[dir]*a + flag2[dir]*b) % k == 0:
            for d in range(n+1):
                stop = (nk)//gcd(nk, d*k+s)
                min_ans = min(min_ans, stop)
                max_ans = max(max_ans, stop)

print(min_ans, max_ans)


a,b,c=input(),input(),input()
if(b==b[::-1] and c=a[::-1]):
    print("YES")
else:
    print("NO")


matrix = [[],[0],[0],[0]]

for i in range(1,4):
	for j in range(3):
		matrix[i].append(int(input()))

if(matrix[1][1] == matrix[3][3] && matrix[1][3] == matrix[3][1] && matrix[1][2] == matrix[3][2] && matrix[2][1] == matrix[2][3]):
	print('YES')
else:
	print('NO')


#._.
#want to maximize xa+y*int((c-z*a)/w)

def maxi(c, x, y, z, w):
    one = x / z
    two = y / w
    dictx = {}
    def f(a):
        return x*a+y*int((c-z*a)/w)
    for a in range(0, int(c//w)+1):
        dictx[a] = f(a)

    return max(dictx, key = lambda x:dictx[x])
c, x, y, z, w = list(map(int, input().split(' ')))
bad = maxi(c, x, y, z, w)
print(x*bad+y*int((c-z*bad)/w))


input()
print "YES" if len(set(input().lower()))==26 else "NO"


a, b = [int(i) for i in input().split()]
o = a - b
sum = 0
l = 1
if o > 0:
    if o ** 0.5 == int(o ** 0.5):
    l = 0
    for i in range(1, int(o ** 0.5) + l):
        if o % i == 0:
            if o // i > b and i > b:
                sum += 2
            if (o // i > b and i <= b) or (o // i <= b and i > b):
                sum += 1
            if i == o // i:
                sum -= 1
if o == 0:
    print('infinity')
else:
    print(sum)


import sys

desired = 'BERLAND'
matches = 5

def check(x, y):
      global result, played, victim
      standing = played.keys()
      for i in range(4):
            points = 0
            team = standing[i]
            got, lost = 0, 0
            for j in range(5):
                  if result[j][1] == team:
                        result[j][0], result[j][1] = result[j][1], result[j][0]
                        result[j][2][0], result[j][2][1] = result[j][2][1], result[j][2][0]
                  if result[j][0] != team:
                        continue
                  diff = result[j][2][0] - result[j][2][1]
                  got += result[j][2][0]
                  lost += result[j][2][1]
                  if diff == 0: points += 1
                  if diff > 0: points += 3
            if team == desired:
                  points += 3
                  got += x
                  lost += y
            if team == victim:
                  got += y
                  lost += x
            standing[i] = (-points, -(got - lost), -got, team)
      standing = sorted(standing)
      return standing[0][3] == desired or standing[1][3] == desired

def add(s):
      global played
      if played.has_key(s):
            played[s] += 1
      else:
            played[s] = 1

result = []
played = dict()
for _ in range(matches):
      buf = raw_input().split()
      add(buf[0])
      add(buf[1])
      buf[2] = list(map(int, buf[2].split(':')))
      result.append(buf)
for pair in played.items():
      if pair[1] == 2 and pair[0] != desired:
            victim = pair[0]
for x in range(1, 100):
      for delta in range(x, 0, -1):
            y = x - delta
            if check(x, y):
                  print str(x) + ':' + str(y)
                  sys.exit(0)
print 'IMPOSSIBLE'