Line=raw_input()
Colors=[]
for c in Line:Colors.append(c)
Global=set()
Ans=0
#print Colors

def LtoS(L):
    S=""
    for c in L:S=S+str(c)
    return S

def moveUp(L):
    Colors2=[0]*6
    Colors2[0]=L[3]
    Colors2[1]=L[5]
    Colors2[4]=L[4]
    Colors2[2]=L[2]
    Colors2[3]=L[1]
    Colors2[5]=L[0]
    return Colors2
def moveRight(L):
    Colors2=[0]*6
    Colors2[0]=L[4]
    Colors2[1]=L[2]
    Colors2[5]=L[5]
    Colors2[3]=L[3]
    Colors2[2]=L[0]
    Colors2[4]=L[1]
    return Colors2
def Turn(L):
    Colors2=[0]*6
    Colors2[0]=L[0]
    Colors2[1]=L[1]
    Colors2[2]=L[5]
    Colors2[4]=L[3]
    Colors2[5]=L[4]
    Colors2[3]=L[2]
    return Colors2

itern=0
FuckingNew=False
for st1 in xrange(6):
    for st2 in xrange(6):
        for st3 in xrange(6):
            for st4 in xrange(6):
                for st5 in xrange(6):
                    for st6 in xrange(6):
                        itern+=1
                        s=set()
                        s.add(st1)
                        s.add(st2)
                        s.add(st3)
                        s.add(st4)
                        s.add(st5)
                        s.add(st6)
                        if(len(s)!=6):continue
                        FuckingNew=False
                        List=[Colors[st1],Colors[st2],Colors[st3],Colors[st4],Colors[st5],Colors[st6]]
                        def check():
                             global FuckingNew
                             global Ans
                            # print List
                             if not LtoS(List) in Global:
                              if not FuckingNew:
                                  Ans=Ans+1
                                  FuckingNew=True
                                #  print Global
                              Global.add(LtoS(List))
                        for c in xrange(4):
                         check()
                         List=Turn(List)
                        List=moveUp(List)
                        for c in xrange(4):
                          check()
                          List=Turn(List)
                        List=moveUp(List)
                        for c in xrange(4):
                          check()
                          List=Turn(List)
                        List=moveUp(List)
                        for c in xrange(4):
                          check()
                          List=Turn(List)
                        List=moveUp(List)
                        for c in xrange(4):
                          check()
                          List=Turn(List)
                        List=moveRight(List)
                        for c in xrange(4):
                           check()
                           List=Turn(List)
                        List=moveRight(List)
                        List=moveRight(List)
                        for c in xrange(4):
                           check()
                           List=Turn(List)

                       # print itern,Global

                        #Kataem:

#print Global
print Ans


a, b = map(int, input().split())
c, d = map(int, input().split())
ans = -1

for i in range(100):
    for j in range(100):
        if i*a+b == c*j+d:
            ans = c*j+d
            print(ans)
            exit()
print(ans)


p, y = [int(x) for x in input().split()]
res = -1
for i in range(y, p, -1):
    flag = True
    for a in range(2, min(p+1, int(i**0.5)+1)):
        if i % a == 0:
            flag = False
            break
    if flag:
        res = i
        break
print(res)


a, b = [int(x) for x in input().split(' ')]
if abs(a - b) <= 1 and max(a, b) > 0:
    print('YES')
else:
    print('NO')


import math
a,b,n=map(int,input().split())
c=0
while(n!=0):
    if(n>0):
        n-=math.gcd(a,n)
        c+=1
        #print(n)
    if(n>0):
        n-=math.gcd(b,n)
        #print(n)
        c+=1

if(c%2!=0):
    print("0")
else:
    print("1")


from functools import lru_cache
import itertools
def invnum(seq):
    N=len(seq)
    res=0
    for i in range(N):
        for j in range(i+1,N):
            if seq[i]>seq[j]:
                res+=1
    return res
def naive(N,k,flag):
    res=0
    for p in itertools.permutations(range(N),N):
        for q in itertools.permutations(range(N),N):
            if ((p<q) or (not(flag))) and (invnum(p)-invnum(q)>k):
                res+=1
    return res
n,mod=map(int,input().split())
memo=[[{},{}] for _ in range(n+1)]
def solve(N,k,flag):
    if k in memo[N][flag]:
        return memo[N][flag][k]
    '''
    長さNの順列
    invnum(p)-invnum(q)>kとなる場合の数
    flag=True p<qの条件あり
    flag=False p<qの条件なし
    '''
    if N==1:
        res=-1
        if flag:
            res=0
        else:
            if k<0:
                res=1
            else:
                res=0
        memo[N][flag][k]=res
        return res
    invnum_INF=(N*(N-1))//2
    if k<-invnum_INF-1:
        res=solve(N,-invnum_INF-1,flag)
        memo[N][flag][k]=res
        return res
    if k>=invnum_INF:
        memo[N][flag][k]=0
        return 0
    res=0

    for delta in range(-N+1,N):
        if flag and (delta>0):
            continue
        wt=min(N-delta,delta+N)
        res+=solve(N-1,k-delta,(delta==0)&flag)*wt
        res%=mod
    memo[N][flag][k]=res%mod
    return res%mod
ans=solve(n,0,1)%mod
print(ans)


import sys
stdin = sys.stdin

n, q = map(int, stdin.readline().strip().split())

qs = []
for i in range(q):
    aa, bb = stdin.readline().strip().split()
    qs.append((list(reversed(aa)), bb))

sts = set()
def dfs(have):
    if len(have) == n:
        sts.add(''.join(have))
    else:
        for aa, bb in qs:
            if have[-1] == bb:
                dfs(have[:-1] + aa)

dfs(['a'])
print len(sts)


s=raw_input()
n=input()
m=len(s)
INF = 1000
r = [[[-INF]*2 for j in range(m+1)] for i in range(m+1)]
l = [[[INF]*2 for j in range(m+1)] for i in range(m+1)]
for k in range(2):
    r[0][0][k] = 0;l[0][0][k] = 0
for i in range(m):
    for j in range(i+1):
        for k in range(2):
        # move forward
            c = s[i]=='T'
            if k==1:
                l[i+1][j+c][k] = min (l[i+1][j+c][k], l[i][j][k]+1)
                r[i+1][j+c][k] = max (r[i+1][j+c][k], r[i][j][k]+1)
            else:
                l[i+1][j+c][k] = min (l[i+1][j+c][k], l[i][j][k]-1)
                r[i+1][j+c][k] = max (r[i+1][j+c][k], r[i][j][k]-1)
            # turn
            c = s[i]=='F'
            l[i+1][j+c][k] = min (l[i+1][j+c][k], l[i][j][1-k])
            r[i+1][j+c][k] = max (r[i+1][j+c][k], r[i][j][1-k])

ans = -INF
for k in range(2):
    for j in range(min(n,m)+1):
        if j%2==n%2:
            ans = max(ans,-l[m][j][k])
            ans = max(ans,r[m][j][k])
print ans


s = input() + 'X' * int(input())
for v in range(len(s) - len(s) % 2, 0, -2):
    for i in range(len(s) - v + 1):
        if all(s[j + v // 2] in ('X', s[j]) for j in range(i, i + v // 2)):
            print(v), exit()


import sys
from collections import defaultdict
n = int(sys.stdin.readline())
cards = sys.stdin.readline().strip().split()
first = set()
second = set()
cur = tuple(cards[-4:])
first.add(cur)

#print cur

for i in xrange(n-1,0,-1):
    #print "i = ", i
    second = set()
    for elem in first:
        #print "elem =", elem
        newList = [cards[i-4]] if i-4 >= 0 else []
        #print "newList =", newList
        if elem[-1][0] == elem[-2][0] or elem[-1][1] == elem[-2][1]:
            anotherTuple = tuple(newList + list(elem)[:-2] + [elem[-1]])
            second.add(anotherTuple)
        if len(elem) == 4 and (elem[-1][0] == elem[0][0] or elem[-1][1] == elem[0][1]):
            anotherTuple = tuple(newList + [elem[3]] + [elem[1]] + [elem[2]])
            second.add(anotherTuple)
    first = second

print 'YES' if len(first) > 0 else 'NO'


import math
import sys

def main():
  n = int(raw_input())
  s = raw_input()
  for i in range(1, 100): # jump length
    for j in range(len(s)): # start index
      good = True
      for k in range(5): # jumps
        if j + k*i >= n or s[j + k*i] == '.':
          good = False
          break
      if good:
        print 'yes'
        return
  print 'no'

if __name__ == '__main__':
  main()


x,y,z,k=map(int,raw_input().split())
x,y,z = sorted([x,y,z])
x-=1
y-=1
z-=1
if x>k/3: x=k/3
k-=x
if y>k/2: y=k/2
k-=y
if z>k: z=k

print (x+1)*(y+1)*(z+1)


import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n,a,b=map(int,input().split())

if a<b: a,b=b,a

if b==0:
    # 1 01 001 0001 ... is optimal, plus a long series of 0's
    print((n-1)*a)
else:
    # pascal's triangle thing
    pascal=[[1]*20005]
    for i in range(20004):
        newrow=[1]
        for j in range(1,20005):
            newrow.append(newrow[-1]+pascal[-1][j])
            if newrow[-1]>n: break
        pascal.append(newrow)
    def getcom(a,b):
        # return a+b choose b
        # if larger than n, return infinite
        if len(pascal[a])>b: return pascal[a][b]
        if b==0: return 1
        if b==1: return a
        return 100000005

    # start with the null node (prefix cost 0)
    # can split a node into two other nodes with added cost c+a+b
    # new nodes have prefix costs c+a, c+b
    # want n-1 splits in total
    remain=n-1
    ans=0
    possible=[[a+b,1]]    # [c,count]
    while 1:
        # cost u, v leaves
        u,v=heapq.heappop(possible)
        while possible and possible[0][0]==u:
            v+=possible[0][1]
            heapq.heappop(possible)
        if remain<=v:
            ans+=u*remain
            break
        ans+=u*v
        remain-=v
        heapq.heappush(possible,[u+a,v])
        heapq.heappush(possible,[u+b,v])
    print(ans)


(n,m)=map(int, raw_input().split())
count=0
for i in range(0,n):
    p=(i+1)%5
    count=count+(p+m)/5;
print count


#D razbor 1

def func(n):
    if n<8:
        return n,n

    max_a = int(n**(1/3))
    if (max_a+1)**3<=n:
        max_a += 1

    v1=func(n-max_a**3)
    v1=(v1[0]+1,v1[1]+max_a**3)

    v2=func(max_a**3-1-(max_a-1)**3)
    v2=(v2[0]+1,v2[1]+(max_a-1)**3)

    if v2>v1:
        return v2
    else:
        return v1

print(' '.join(map(str, func(int(input())))))


def find(n,k):
    if k==0:
        return False
    count=0
    t=n
    while n>0:
        if n<k:
            count+=n
            n=0
        else:
            count+=k
            n-=k
        n=n-n//10
    if 2*count>=t:
        return True
    else:
        return False

def binarySearch(l,r,n):
    while l<=r:
        mid=l+(r-l)//2
        c=find(n,mid)
        c1=find(n,mid-1)
        c2=find(n,mid+1)
        if c and not c1:
            return mid
        elif c:
            r=mid-1
        else:
            l=mid+1

n=int(input())
print(binarySearch(1,n,n))


i = input()
x = int(i)
cont = 0
while x:
    x -= int(max(i))
    i = str(x)
    cont += 1
print(cont)


#!/usr/bin/env python3

import itertools

notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']

n = [notes.index(n) for n in input().strip().split()]

for (X,Y,Z) in itertools.permutations(n):
  d1 = Y-X
  if (d1 < 0):
    d1+=12
  d2 = Z-Y
  if (d2 < 0):
    d2+=12
  if (d1 == 4) and (d2 == 3):
    print("major")
    exit()
  if (d1 == 3) and (d2 == 4):
    print("minor")
    exit()

print("strange")


from math import factorial as fact
n = input ()
M = 1000000007

def egcd (a, b):
    if a % b == 0:
        return (0, 1)
    x = egcd (b, a % b)
    return (x[1], x[0] - x[1] * (a / b))

def C (n, k):
    a = 1
    for i in xrange (n - k + 1, n + 1):
        a *= i
        a %= M
    b = 1
    for i in xrange (1, k + 1):
        b *= i
        b %= M
    return (a * egcd (b, M)[0]) % M

print (2 * C (n * 2 - 1, n) - n) % M


import bisect
def LIS(As):
    L = [As[0]]
    for a in As[1:]:
        if a >= L[-1]:
            L.append(a)
        else:
            pos = bisect.bisect_right(L, a)
            L[pos] = a
    return L

def solve():
    n,T = map(int,input().split())
    array = list(map(int,input().split()))
    if (T<=n+1):
        print (len(LIS(array*T)))
    else:
        newarray = array*n
        lis = LIS(newarray)
        newlis = LIS(newarray+array)
        print (len(newlis)+(len(newlis)-len(lis))*(T-n-1))

solve()


import math
import random
import sys

def main(s):

    if (len(s)==1 and (s[0]=="0" or s[0]=="_" or s[0]=="X")):
        return 1
    elif (s[0]=="0" and len(s)>1):
        return 0
    elif (len(s)==1):
        return 0
    mult1=1
    mult2=1
    f=False
    for i in range(len(s)-2):

        if s[i]=="_":
            if (i!=0):
                mult1*=10
            else:
                mult1*=9
        elif s[i]=="X" and mult2==1:
            if (i!=0):
                mult2=10
            else:
                mult2=9
                f=True
    ans=0
    for i in range(100):
        if (i%25)!=0:
            continue
        val=list([c for c in str(i)])
        if (i==0):
            val=["0","0"]

        mult_val=mult2
        check=[s[-2],s[-1]]

        if check[0]=="X":
            if (val[0]=='0' and f):
                continue
            check[0]=val[0]
            mult_val=1
            if check[1]=="X":

                check[1]=val[0]

        if (check[1]=="X" and check[0] !="X"):
            if (val[1]=='0' and f):
                continue
            check[1]=val[1]
            mult_val=1
        if (check[0]=="_"):
            check[0]=val[0]
        if (check[1]=="_"):
            check[1]=val[1]
        if (val==check) and not (len(s)==2 and check[0]=="0"):
            ans+=mult_val*mult1

    return ans

s=input()
print(main(s))


from fractions import gcd

n = input()
H = dict()
inf = 10000000

def number (n,b):
    s = 0
    while b>1:
        s += n/b
        n,b = b,n%b
    if b==1: return s+n-1
    else:    return inf

m = inf
for b in range(1,(n+1)/2+1):
    m = min (number(n,b),m)
print m


import math

def cnt(n, x):
    res = 0
    while n > x:
        n //= 2
        res += 1
    if n == x:
        return res
    return -1

def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    b = set()
    b.add(0)
    for i in a:
        while i > 0:
            b.add(i)
            i //= 2
    ans = int(10e9)
    for x in b:
        s = []
        for i in a:
            c = cnt(i, x)
            if c >= 0:
                s.append(c)
        s.sort()
        if len(s) >= k:
            l = sum(s[:k])
            ans = min(ans, l)
    print(ans)

main()


from operator import itemgetter

n = list(map(int, list(input())))
l = n[:3:]
r = n[3::]
ls = sum(l)
rs = sum(r)

ans = []
ans1 = []
for i in range(3):
    ans.append([9 - l[i], 1])
    ans.append([r[i], 2])
    ans1.append([9 - r[i], 2])
    ans1.append([l[i], 1])
cnt = 0
ans.sort(key=itemgetter(0), reverse=True)
ans1.sort(key=itemgetter(0), reverse=True)
if ls < rs:
    i = 0
    while ls < rs:
        if ans[i][1] == 1:
            ls += ans[i][0]
            cnt += 1
        else:
            rs -= ans[i][0]
            cnt  += 1
        i += 1
    print(cnt)

elif ls > rs:
    i = 0
    while ls > rs:
        if ans1[i][1] == 1:
            ls -= ans1[i][0]
            cnt += 1
        else:
            rs += ans1[i][0]
            cnt  += 1
        i += 1
    print(cnt)

else:print(0)


n,m=map(int,input().split())
a=list(map(int,input().split()))
t=list(map(int,input().split()))
x=sum(t)
for i in range(n-x+1):
    freq=[0]*m
    for j in range(i,i+x):
        freq[a[j]-1]+=1
    flag=True
    for j in range(m):
        if freq[j]!=t[j]:
            flag=False
            break
    if flag:
        break
if flag:
    print("YES")
else:
    print("NO")


s=raw_input().strip()
y,x=0,0
seen=[(y,x)]
b=False
for i in s:
    if i=='L':x-=1
    elif i=='R':x+=1
    elif i=='U':y-=1
    else:y+=1
    co=0
    for y2,x2 in seen:
        if abs(y2-y)+abs(x2-x)<=1:
            co+=1
    seen.append((y,x))
    if co>1:b=True
print 'BUG' if b else 'OK'


from sys import stdin
n=int(stdin.readline().strip())
x=n-2+n-3+n-3+(n-4)*(n-3)
print(x)


li=lambda:(map(int,raw_input().strip().split()))
ni=lambda:(int(raw_input()))
si=lambda:(raw_input())
import math
from collections import Counter
n=ni()
r=si()
l=len(r)
g=1
for i in range(0,l-1):
    if r[i]==r[i+1]:
        if r[i]=="?":
            continue
        else:
            print "No"
            exit(0)
i=0
if r[i]=="?" or r[l-1]=="?":
    print "Yes"
    exit(0)
for i in range(1,l-2):
    if r[i]=="?":
        if r[i-1]!=r[i+1] and r[i-1]!="?" and r[i+1]!="?":
            g=1
        else:
            g=2
            print "Yes"
            exit(0)
            break
if g==1:
    print "No"


lst=list(map(int,input().split()))
d={}
for k in lst:
    d[k]=lst.count(k)
sm=[]
for k in d:
    if d[k]==2:
        sm.append(d[k]*k)
    elif d[k]>=3:
        sm.append(k*3)

if len(sm)!=0:
    print(sum(lst)-max(sm))
else:
    print(sum(lst))


#import resource
import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#threading.Thread(target=main).start()
#import threading
#threading.stack_size(2**26)
#sys.setrecursionlimit(10**7)
mod=(10**9)+7
#fact=[1]
#for i in range(1,1001):
#    fact.append((fact[-1]*i)%mod)
#ifact=[0]*1001
#ifact[1000]=pow(fact[1000],mod-2,mod)
#for i in range(1000,0,-1):
#    ifact[i-1]=(i*ifact[i])%mod
from sys import stdin, stdout
#from bisect import bisect_left as bl
#from bisect import bisect_right as br
#import itertools
#import math
#import heapq
#from random import randint as rn
#from Queue import Queue as Q
def modinv(n,p):
    return pow(n,p-2,p)
def ncr(n,r,p):
    t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p
    return t
def ain():
    return map(int,sin().split())
def sin():
    return stdin.readline().strip()
def GCD(x, y):
   while(y):
       x, y = y, x % y
   return x
def comp(a,b):
    if(a[1]>b[1]):
        return 1
    elif(a[1]<b[1]):
        return -1
    else:
        if(a[0]>b[0]):
            return 1
        else:
            return -1
"""**************************************************************************"""
n=input()
s=0
for i in range(2,n):
    k=i*(i+1)
    s+=k
print s


def next(dx, dy):
    return ([(dx,dy+1), (dx, dy-1)] if dy == 0 else [(dx+1,dy), (dx-1, dy)] if dx * dy == 0 else [(dx,0), (0, dy)])
visited = set()
states = set()
n = int(raw_input())
T = map(int, raw_input().split())
states.add((0,0,0,1))
for t in T:
    new_states = set()
    for x,y,dx,dy in states:
        cnt = 0
        for k in range(1, t + 1):
            visited.add((x + k * dx, y + k * dy))
            cnt += 1
        next_dirs = next(dx, dy)
        for ndx, ndy in next_dirs:
            new_states.add((x + t*dx, y + t*dy, ndx, ndy))
    states = new_states
print len(visited)


hh,mm=input().split(":")
a=int(input())
m=int(hh)*60+int(mm)+a
m=m%1440
hh,mm=m//60,m%60
if hh<10:
    hh='0'+str(hh)
if mm<10:
    mm='0'+str(mm)
print("{}:{}".format(hh,mm))


a,N,K=[0]+[int(i)for i in input().split()]
d=lambda n:sum([min(N-(n<<e)+1,1<<e)for e in range(99)if n<<e<=N])
c=lambda n:d(n)+(d(n+1),0)[n&1]
for b in range(59,-1,-1):a+=1<<b if c(a+2**b)>=K else 0
print(a)
    # print('b: ', b)
    # print('a+2**b: ', a+2**b)
    # print('c: ', c(a+2**b,b))
    # print('a: ', a)
    # print()
# print()
# print(c(4,2))
# print(c(6,1))
# print(d(6))
# print(d(7))
# print(d(3))


modu = 10 ** 9 + 7

def S(x):
	if x == 0:
		return 0
	if x & 1:
		return 11 * pow(3, x / 2, modu) - 7
	else:
		return 19 * pow(3, x / 2 - 1, modu) - 7

def T(x):
	return (S(x) + S((x + 1) / 2)) * pow(2, modu - 2, modu) % modu

[l, r] = [int(x) for x in raw_input().split(' ')]
print (T(r) - T(l - 1) + modu) % modu


x, y = map(int, input().split())
p = x * x + y * y
d = int(p ** 0.5)
if d * d == p: print('black')
else:
    if x * y < 0: print('black' if d % 2 else 'white')
    else: print('white' if d % 2 else 'black')


n,m=[int(k) for k in raw_input().split(" ")]

if m>n:
    m,n=n,m

if m>=3:
    if (m*n)%2:
        print m*n-1
    else:
        print m*n
elif m==2:
    if n==2:
        print 0
    elif n==3:
        print 4
    elif n==7:
        print 12
    else:
        print n*m
else:
    n6=n%6
    nn=(n/6)*6
    if n6==5:
        nn+=4
    if n6==4:
        nn+=2
    print nn


def chk(x,y,x1,y1,x2,y2):
    if x==x1 or y==y1:
        return False
    if x==x2 and y==y2:
        return False
    if abs(x-x1)*abs(y-y1)==2:
        return False
    if abs(x-x2)*abs(y-y2)==2:
        return False
    return True

s=input()
x1=ord(s[0])-ord('a')
y1=int(s[1])-1
s=input()
x2=ord(s[0])-ord('a')
y2=int(s[1])-1
ans=0
for i in range(8):
    for j in range(8):
        if chk(i,j,x1,y1,x2,y2):
            ans+=1
print(ans)


#	!/usr/bin/env python3
#	coding: UTF-8
#	Modified: <06/Feb/2019 07:48:18 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

#	Question Link
#
#

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

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

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

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

# ///==========MAIN=============///

graph = [[] for _ in range(405)]
graph_reverse = [[] for _ in range(405)]
visited = [False] * 405
visited_other = [False] * 405
stack = []
scc = 0

def explore(node):
    visited[node] = True
    for neighbour in graph_reverse[node]:
        if visited[neighbour] == False:
            explore(neighbour)
    stack.append(node)

def dfs(n, m):
    for i in range(n):
        for j in range(1, m + 1):
            if visited[i * m + j] == False:
                explore(i * m + j)

def explore_other(node):
    visited_other[node] = True
    for neighbour in graph[node]:
        if visited_other[neighbour] == False:
            explore_other(neighbour)

def dfs_o(n, m):
    global scc
    for node in reversed(stack):
        if visited_other[node] == False:
            scc += 1
            #print(node, scc)
            explore_other(node)

def main():
    n, m = get_ints()
    horizontal = input().strip()
    for i in range(n):
        if horizontal[i] == '<':
            for j in range(1, m):
                graph[i * m + j + 1].append(i * m + j)
                graph_reverse[i * m + j].append(i * m + j + 1)
        else:
            for j in range(1, m):
                graph[(i) * m + j].append(i * m + (j + 1))
                graph_reverse[i * m + (j + 1)].append((i) * m + j)
    vertical = input().strip()
    for j in range(1, m + 1):
        if vertical[j - 1] == '^':
            for i in range(n - 1):
                graph[(i + 1) * m + j].append((i) * m + (j))
                graph_reverse[(i) * m + (j)].append((i + 1) * m + j)
        else:
            for i in range(n - 1):
                graph[i * m + j].append((i + 1) * m + (j))
                graph_reverse[(i + 1) * m + (j)].append((i) * m + j)
    '''for i in range(n + 1):
        for j in range(1, m + 1):
            print(graph[i * m + j], end=' ')
        print()
    print('next')
    for i in range(n + 1):
        for j in range(1, m + 1):
            print(graph_reverse[i * m + j], end=' ')
        print()'''

    dfs(n, m)
    # print(stack)
    dfs_o(n, m)
    print('YES' if scc == 1 else 'NO')

if __name__ == "__main__":
    main()


def rf():
    cs = list(map(int, input().split(' ')))
    cs = list(zip(cs[0::2], cs[1::2]))
    return cs

def cross(p, p1, p2):
    return (p2[1] - p[1]) * (p1[0] - p[0]) - (p2[0] - p[0]) * (p1[1] - p[1])

def inside(p, f):
    os = 0
    total = 0
    for i in range(len(f)):
        p1 = f[i]
        p2 = f[(i+1)%len(f)]
        delta = cross(p, p1, p2)

        os += delta
        total += abs(delta)

    os = abs(os)
    return os == total

#for yy in range(0, 7):
#    for xx in range(0, 7):
#        #print(inside((xx, yy), [(4, 0), (5, 1), (4, 2), (3, 1)]), end=' ')
#        #print(inside((xx, yy), [(2, 1), (3, 1), (3, 4), (2, 4)]), end=' ')
#        #print(inside((xx, yy), [(3, 1), (5, 3), (3, 5), (1, 3)]), end=' ')
#    print()
#exit()

fs = [rf(), rf()]

res = False
for fi in range(2):
    f1 = fs[fi]
    f2 = fs[1-fi]
    for pi in range(len(f1)):
        cur = inside(f1[pi], f2)
        res = res or cur

    res = res or inside( ((f1[0][0] + f1[2][0]) // 2, (f1[0][1] + f1[2][1]) // 2), f2 )

print(['NO', 'YES'][res])


from math import *
k, n, s, p = map(int, input().split())
q = k * ceil(n / s)
w = ceil(q / p)
print(w)


(n,h,m) = [int(x) for x in input().split()]
houses= [h]*n
for i in range(m):
    (l,r,x) = [int(x) for x in input().split()]
    for j in range(l-1,r):
        houses[j] = min(houses[j],x)

mx = 0
for j in range(n):
    mx += houses[j]*houses[j]

print(mx)


def gcd(m, n):
	return m if not n else gcd(n, m%n)
n = int(input())
cnt = 0
for i in range(2, int(n**0.5)+2):
	for j in range(1+i%2, i, 2):
		if gcd(i,j)==1:
			cnt += n//(i*i+j*j)
print(cnt)


n, t = input(), [0] * 1002
for i in map(int, input().split()): t[i] += 1
T = int(input()) + 1
for i in range(1000): t[i + 1] += t[i]
print(max(t[i + T] - t[i] for i in range(-1, 1001 - T)))


G = list(map(int, input().split()))
N = G[0]
M = G[1]

if M > 1:
  print(N * (M - 1))
else:
  print(M * (N - 1))


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

poss_Splits = []
ps = 0
ptlan = 0
for i in range(n - 1):
    if arr[i] % 2 == 0:
        ps += 1
    else:
        ptlan += 1
    if ps == ptlan:
        poss_Splits.append((abs(arr[i] - arr[i + 1]), i))

poss_Splits = sorted(poss_Splits)
i = 0
while i < len(poss_Splits) and B >= poss_Splits[i][0]:
    B -= poss_Splits[i][0]
    i += 1

print(i)


#from math import *
#from collections import Counter
def rl(s): return xrange(len(s))

INF = 2147483647

import sys
stdin = sys.stdin

a, ta = map(int, stdin.readline().strip().split())
b, tb = map(int, stdin.readline().strip().split())
simion = map(int, stdin.readline().strip().split(':'))
simion = simion[0]*60 + simion[1] - 5*60

b_starts = [0]
while True:
    nextb = b_starts[-1] + b
    if nextb > (23-5)*60+59:
        break
    b_starts.append(nextb)

#print b_starts

rr = 0
for bst in b_starts:
    b_end = bst + tb
    if b_end > simion and bst < simion + ta:
        rr += 1

print rr


mod = 1000000007
n,k = [int(x)for x in input().split()]
dp = [[0 for i in range(n+1)]for j in range(k+1)]

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

for l in range(2,k+1):
	for i in range(1,n+1):
		for j in range(i,n+1,i):
			dp[l][j] += dp[l-1][i]
			if(dp[l][j] >= mod):
				dp[l][j] -= mod
sum = 0
for i in range(1,n+1):
	sum += dp[k][i]
	if sum >= mod:
		sum -= mod
print(sum)


import math
for _ in range(int(input())):
    n=int(input())
    if n%2==0:
        print(n//2,n//2)
    else:
        flag=0
        for i in range(2,int(math.sqrt(n))+1):
            if n%i==0:
                temp=i
                flag=1
                break
        if flag==0:
            print(1,n-1)

        else:
            x=n//temp
            print(x,(temp-1)*x)


n, m = [int(x) for x in raw_input().split(' ')]
if m <= 1:
    print 1
elif m <= (n / 2):
    print m
else:
    print (n - m)


n = input()
n = int(n)
#print(n)
if (n < 46):
    a = 0
    while n:
        if (n >= 10):
            a = a * 10 + 9
            n -= 9;
        else:
            a = a * 10 + n
            n = 0
    print(a, a)
    exit(0)
p = 1
for i in range(1,n):
    p *= 10
    m = p // 10 * i * 45 + 1
    #print(m, p, m + p)
    if (m + p > n):
        k = n - m
        while k < 0:
            k += n
        if (k >= p):
            continue
        print(k + 1, p + k)
        exit(0)


n,t = map(int, raw_input().split())
c = n*(n+1)/2
a = [0] * c
a[0] = t
counter = 0
level = 0
for i in range(c):
	if (a[i] > 1):
		rem = a[i] - 1
		a[i] = 1
		if i+ level + 1 < c:
			a[i + level + 1] += rem/2.0
		if i+ level+ 2 < c:
			a[i + level + 2] += rem/2.0
	if i == counter:
		level += 1
		counter += level + 1;
print a.count(1)


from sys import stdin

(x, y) = [int(buf) for buf in stdin.readline().strip().split()]

k = min(x//2, y//24)

x -= 2 * k
y -= 24 * k

ans = 0
while y >= 2 and x*100 + y*10 >= 220:
    ans = 1 - ans
    if ans == 1:
        y -= 22 - min(x, 2) * 10
        x -= min(x, 2)
    else:
        x -= 2 - min((y-2)//10, 2)
        y -= 2 + min((y-2)//10, 2) * 10

print('Ciel' if ans == 1 else 'Hanako')


x=map(int,raw_input().split(' '))
n=x[0]
m=x[1]
s=x[2]
tmp=(n%s)*((n/s)+1)
tmp=n if (tmp==0) else tmp
tmp1=(m%s)*((m/s)+1)
tmp1=m if (tmp1==0) else tmp1
print(tmp1*tmp)


a = list(input())
if a[0] == 'f':
    print('ftp://',end = '')
    a = a[3:]
    while len(a[:''.join(a).index('ru')]) == 0:
        if len(a[:''.join(a).index('ru')]) != 0:
            print(''.join(a[:''.join(a).index('ru')]),end = '')
        else:
            print('ru',end = '')
            a = a[''.join(a).index('ru')+2:]
    print(''.join(a[:''.join(a).index('ru')]),end = '')
    a = a[''.join(a).index('ru')+2:]
    print('.ru',end='')
    if len(a) != 0:
        print('/',end='')
        print(''.join(a))
else:
    print('http://',end = '')
    a = a[4:]
    while len(a[:''.join(a).index('ru')]) == 0:
        if len(a[:''.join(a).index('ru')]) != 0:
            print(''.join(a[:''.join(a).index('ru')]),end = '')
        else:
            print('ru',end = '')
            a = a[''.join(a).index('ru')+2:]
    print(''.join(a[:''.join(a).index('ru')]),end = '')
    a = a[''.join(a).index('ru')+2:]
    print('.ru',end='')
    if len(a) != 0:
        print('/',end='')
        print(''.join(a))


# vars: A, B, k, k1, n, res, x
n = int(input())
k = int(input())
A = int(input())
if k == 1:
	print((n-1)*A)
	exit()
B = int(input())
res = 0
x = n
k1 = (k-1)*A
while x > 1:
	res += A*(x % k)
	x //= k
	if x:
		if B > x * k1:
			res += (x*k-1)*A
			x = 1
		else:
			res += B
print(res-(1-x)*A)
# a, b -> a // b, a % b


__author__ = 'Darren'

# d(x) = (x-1) % 9 + 1
def solve():
    n = int(input())

    # count[i]: the number of x's in [1,n] such that d(x) = i
    count = [0] * 10
    for i in range((n-1) % 9 + 2):
        count[i] = (n + 8) // 9
    for i in range((n-1) % 9 + 2, 10):
        count[i] = n // 9

    result = 0

    # Count all triples (i, j, k) such that d(d(i)*d(j)) = d(k)
    for i in range(1, 10):
        for j in range(1, 10):
            result += count[i] * count[j] * count[(i*j-1) % 9 + 1]

    # For each i, there are n/i triples (i,j,k) such that i*j = k,
    # i.e., the correct cases
    for i in range(1, n+1):
        result -= n // i

    print(result)

if __name__ == '__main__':
    solve()


R = lambda: map(int, input().split())
s = input()
cc, c = 0, 0
for r in range(len(s)):
    if r == 0 or s[r] == s[r - 1]:
        c += 1
    else:
        cc += (c % 2 == 0)
        c = 1
cc += (c % 2 == 0)
print(cc)


def is_intersect(r1, r2, R, x1, y1, x2, y2):
    d = (x1 - x2)**2 + (y1 - y2)**2
    return d >= (r1 + R)**2 or r1 < r2 and d <= (r2 - r1)**2 or R < r1 and d <= (r1 - R)**2

x1, y1, r1, R1 = map(int, input().split())
x2, y2, r2, R2 = map(int, input().split())

res1 = is_intersect(r1, r2, R2, x1, y1, x2, y2)
res2 = is_intersect(R1, r2, R2, x1, y1, x2, y2)
res3 = is_intersect(r2, r1, R1, x2, y2, x1, y1)
res4 = is_intersect(R2, r1, R1, x2, y2, x1, y1)

print(res1 + res2 + res3 + res4)


def lucky(x):
  while x>0:
    d=x%10
    x/=10
    if d!=4 and d!=7:
      return False
  return True
n,k=map(int,raw_input().split())
k-=1
p=[1]*16
for i in xrange(13):p[i+1]=p[i]*(i+1)
a=[]
def n_th(x):
  if n-x<13:
    return a[x-1-n]+max(0,n-13)+1
  else:
    return x
if n<=13 and k>=p[n]:print -1
else:
  s=[1]*16
  for b in reversed(xrange(min(13,n))):
    u=0
    while k>=p[b]:
      k-=p[b]
      while not s[u]:u+=1
      u+=1
    while not s[u]:u+=1
    a.append(u)
    s[u]=0
  t=0
  for w in xrange(1,10):
    for x in xrange(1<<w):
      y=0
      for b in xrange(w):
        y=y*10+(7 if ((1<<b)&x) else 4)
      if y<=n and lucky(n_th(y)):t+=1
  print t


def main():
    w, m, k = map(int, raw_input().split())
    count = 0
    while w > 0:
        bits = len(str(m))
        number = ((10**bits)-1-m+1)
        if number * bits * k <= w:
            w -= number * bits * k
            count += number
            m = 10**bits
        else:
            count += w / (len(str(m))*k)
            break
    print count

if __name__ == '__main__':
    main()


import math
n, m = map(int, input().split())
f = [0] * (n + 1)
ans = 1
sum = [0]
k = int(math.log2(n))
tmp = [0] * (int(k+1) * m)
for i in range(1, k + 1):
    sum.append(sum[-1])
    for j in range(1, m + 1):
        if tmp[i * j] == 0:
            sum[-1] += 1
            tmp[i * j] = 1
for i in range(2, n + 1):
    if f[i] == 1:
        continue
    now, v = i, 0
    while now <= n:
        f[now] = 1
        now *= i
        v += 1
    ans += sum[v]
print(ans)


w,b,k,p,q=map(float,raw_input().split()+[0,0,1])
s=w+b
while q and k<s:
    d=q*w/s
    p+=d;q-=d;s-=1
    d=q*w/s
    q-=d;s-=1;k+=1
print p


# Contest: 21 - Codeforces Rating >= 2200 (https://a2oj.com/ladder?ID=21)
# Problem: (25) Hexagons (Difficulty: 5) (http://codeforces.com/problemset/problem/615/E)

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

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

SIDES = [
    lambda c, v: (1 + 2 * c - v, 2 + 2 * v),
    lambda c, v: (-1 + c - 2 * v, 2 + 2 * c),
    lambda c, v: (-c - 2 - v, 2 * c - 2 * v),
    lambda c, v: (-1 - 2 * c + v, -2 - 2 * v),
    lambda c, v: (1 - c + 2 * v, -2 - 2 * c),
    lambda c, v: (2 + c + v, -2 * c + 2 * v),
]

n = rint()
if n == 0:
    print(0, 0)
    exit(0)
n -= 1
l, h = 0, 10**9
while h - l > 1:
    m = (h + l) // 2
    if 3 * m * (m + 1) > n:
        h = m - 1
    else:
        l = m
c = h if 3 * h * (h + 1) <= n else l
n -= 3 * c * (c + 1)

print(*SIDES[n // (c + 1)](c, n % (c + 1)))


import random

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

def _try_composite(a, d, n, s):
    if pow(a, d, n) == 1:
        return False
    for i in range(s):
        if pow(a, 2**i * d, n) == n - 1:
            return False
    return True

def is_prime(n):
    if n in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]:
        return True

    if (any((n % p) == 0 for p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])) or (n in [0, 1]):
        return False

    d, s = n - 1, 0
    while not d % 2:
        d, s = d >> 1, s + 1

    if n < 2047:
        return not _try_composite(2, d, n, s)
    if n < 1373653:
        return not any(_try_composite(a, d, n, s) for a in [2, 3])
    if n < 25326001:
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5])
    if n < 118670087467:
        if n == 3215031751:
            return False
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7])
    if n < 2152302898747:
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7, 11])
    if n < 3474749660383:
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7, 11, 13])
    if n < 341550071728321:
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7, 11, 13, 17])
    if n < 3825123056546413051:
        return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7, 11, 13, 17, 19, 23])
    return not any(_try_composite(a, d, n, s) for a in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])

def _factor(n):
    for i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]:
        if n % i == 0:
            return i

    y, c, m = random.randint(1, n - 1), random.randint(1, n - 1), random.randint(1, n - 1)
    g, r, q = 1, 1, 1

    while g == 1:
        x = y
        for i in range(r):
            y = ((y * y) % n + c) % n
        k = 0
        while (k < r) and (g == 1):
            ys = y
            for i in range(min(m, r - k)):
                y = ((y * y) % n + c) % n
                q = q * (abs(x - y)) % n
            g = gcd(q, n)
            k = k + m
        r = r * 2

    if g == n:
        while True:
            ys = ((ys * ys) % n + c) % n
            g = gcd(abs(x - ys), n)
            if g > 1:
                break

    return g

n, k = map(int, raw_input().split(' '))
inv = [pow(i, 1000000005, 1000000007) for i in range(60)]

if n == 1:
    print(1)
    exit()

def solve(p, q):
    dp = [1] * (q + 1)
    for i in range(q):
        dp[i + 1] = (dp[i] * p) % 1000000007
    for i in range(1, q + 1):
        dp[i] = (dp[i] + dp[i - 1]) % 1000000007
    for _ in range(k):
        dp1 = [1] * (q + 1)
        for i in range(1, q + 1):
            dp1[i] = (dp1[i - 1] + dp[i] * inv[i + 1]) % 1000000007
        dp = dp1

    return (dp[-1] - dp[-2]) % 1000000007

if is_prime(n):
    print(solve(n, 1))
    exit()

sn = int(n**0.5)
if (sn*sn == n) and is_prime(sn):
    print(solve(sn, 2))
    exit()

ans, f = 1, _factor(n)
if is_prime(f) and (f > sn):
    ans = ans * solve(f, 1) % 1000000007
    n /= f

if 4 <= n:
    c = 0
    while n % 2 == 0:
        c += 1
        n /= 2
    if c:
        ans = ans * solve(2, c) % 1000000007

if 9 <= n:
    c = 0
    while n % 3 == 0:
        c += 1
        n /= 3
    if c:
        ans = ans * solve(3, c) % 1000000007

i = 5
while i * i <= n:
    c = 0
    while n % i == 0:
        c += 1
        n /= i
    if c:
        ans = ans * solve(i, c) % 1000000007

    i += 2 if i % 3 == 2 else 4

if n > 1:
    ans = ans * solve(n, 1) % 1000000007

print ans


n,m,k = [int(r) for r in raw_input().split()]

direction = raw_input()
if direction == "to head":
    direction = -1
else:
    direction = 1

mmts = raw_input()

## Stowaway is m, controller k
def calc(time, s, c, d):
    if time >= len(mmts) - 1:
        return -1
    if c == n:
        d = -1
    if c == 1:
        d = 1
    c = c + d
    if mmts[time] == '0':
        ## Moving
        if d == 1:
            if s >= c:
                s = s + 1
            else:
                s = s-1
        else:
            if s > c:
                s = s + 1
            else:
                s = s - 1
        if s > n:
            s = n
        if s < 1:
            s = 1
        if c == s:
            time += 1
            return time
        time += 1
        return calc(time, s, c, d)
    else:
        if c == 1:
            s = n
        elif c == n:
            s = 1
        elif d == 1:
            s = 1
        else:
            s = n
        if c == s:
            time += 1
            return time
        time += 1
        return calc(time, s, c, d)

l = calc(0, m, k, direction)
if l == -1:
    print "Stowaway"
else:
    print "Controller " + str(l)


teams={}
for _ in range(5):
    t1,t2,scores=raw_input().split()
    s1,s2=map(int,scores.split(':'))
    teams[t1]=teams.get(t1) or [0,0,0,t1,0]
    teams[t2]=teams.get(t2) or [0,0,0,t2,0]
    if s1>s2:
        teams[t1][0]-=3
    elif s1<s2:
        teams[t2][0]-=3
    else:
        teams[t1][0]-=1
        teams[t2][0]-=1
    teams[t1][1]-=s1-s2
    teams[t2][1]-=s2-s1
    teams[t1][2]-=s1
    teams[t2][2]-=s2
    teams[t1][4]+=1
    teams[t2][4]+=1
oppo=[t[3] for t in teams.values() if t[3]!='BERLAND' and t[4]<3][0]
for xy in range(1,123):
    for y in range(0,123):
        t1,t2=teams['BERLAND'][:],teams[oppo][:]
        t1[0]-=3
        t1[1]-=xy
        t2[1]+=xy
        t1[2]-=y+xy
        t2[2]-=y
        t1[4]+=1
        t2[4]+=1
        tms=[t for t in teams.values() if t[4]>2]+[t1,t2]
        tms.sort()
        if tms[0][3]=='BERLAND' or tms[1][3]=='BERLAND':
            print '%d:%d'%(y+xy,y)
            exit()
print 'IMPOSSIBLE'


import sys

input = sys.stdin.readline

def solve(ft):
    n, k = map(int, input().split())
    m = 10**9 + 7
    ans = v = 1
    for i in range(1, min(k+1, n+1)):
        v *= (n-i+1) % mo
        v %= mo
        ans += (v * pow(ft[i], m-2, m)) % m
        ans %= mo
    return ans

ft = [0]*(10**5+1)
mo = 10**9 + 7
ft[0], ft[1] = 1, 1
for i in range(2, 10**5+1):
    ft[i] = (ft[i-1] * i % mo) % mo

print(solve(ft))


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

for i in range(21):
    a+=a%m
if a%m:
    print('No')
else:
    print('Yes')


from __future__ import division, print_function
import __pypy__

add = __pypy__.intop.int_add
sub = __pypy__.intop.int_sub
mul = __pypy__.intop.int_mul

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

    zinv = 1.0/z

    def modmuladd(x,y,c):
        ans = sub(add(mul(x,y),c), mul(z, int(zinv*x*y + zinv*c)))
        if ans >= z:
            return ans - z
        elif ans < 0:
            return ans + z
        else:
            return ans

    grid= [0]*(n*m)
    grid[0]=g
    for i in range(1,n*m):
        grid[i]=modmuladd(grid[i-1],x,y)
    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()


# cook your dish here
n=int(input())
minx=miny=maxx=maxy=0
c=[]
dx={}
dy={}
for i in range(4*n+1):
    x,y=map(int,input().split(' '))
    c.append([x,y])
    if x not in dx:
        dx[x]=1
    else:
        dx[x]+=1
    if y not in dy:
        dy[y]=1
    else:
        dy[y]+=1

minx=miny=maxx=maxy=0

for i in sorted(dx.keys()):
    if dx[i]>=2 and minx==0:
        minx=i
        break

for i in sorted(dy.keys()):
    if dy[i]>=2 and miny==0:
        miny=i
        break

for i in list(reversed(sorted(dx.keys()))):
    if dx[i]>=2 and maxx==0:
        maxx=i
        break

for i in list(reversed(sorted(dy.keys()))):
    if dy[i]>=2 and maxy==0:
        maxy=i
        break

for i in c:
    if minx<=i[0]<=maxx and miny<=i[1]<=maxy:
        if (i[0]!=minx and i[0]!=maxx) and (i[1]!=miny and i[1]!=maxy):
            print(i[0],i[1])
            break
    else:
        print(i[0],i[1])
        break


#!/usr/bin/env python3

[n, m, x, y, vx, vy] = map(int, input().strip().split())

# x, y >= 0, x + y > 0
# (d, p, q) : px + qy = d
def mygcd(x, y):
	if x > y:
		d, p, q = mygcd(y, x)
		return d, q, p
	if x == 0:
		return y, 0, 1
	m, r = divmod(y, x)
	d, p, q = mygcd(r, x)
	return d, q - p*m, p

def solve(n, m, x, y, vx, vy):
#	print ('solve', n, m, x, y, vx, vy)
	if vx < 0:
		cx, cy = solve(n, m, n - x, y, -vx, vy)
		if cx < 0:
			return cx, cy
		else:
			return n - cx, cy
	if vy < 0:
		cx, cy = solve(n, m, x, m - y, vx, -vy)
		if cx < 0:
			return cx, cy
		else:
			return cx, m - cy
	# vx, vy is nonnegative
	if vx == 0:
		if x in (0, n):
			return x, m
		else:
			return -1, -1
	if vy == 0:
		if y in (0, m):
			return n, y
		else:
			return -1, -1
	# vx = vy > 0
	d, p, q = mygcd(n, m)
	if (x - y) % d != 0:
		return -1, -1
	if x == y and n == m:
		return n, m
	if x == y:
		return ((m // d) % 2) * n, ((n // d) % 2) * m
	mxy = min(x, y)
	x, y = x - mxy, y - mxy
	n //= d
	m //= d
	x //= d
	y //= d
	c = x - y
	p = (p * c) % m
	q = (-q * c) % n
#	print ('nmxypq', n, m, x, y, p, q, '=', p*n - x, q*m - y)
	if p*n - x < 0:
		p += m * (-((x - p*n) // m))
	if q*m - y < 0:
		q += n * (-((y - q*m) // n))
	return (p % 2) * n * d, (q % 2) * m * d

cx, cy = solve(n, m, x, y, vx, vy)
if cx < 0:
	print (-1)
else:
	print (cx, cy)


aaa =0

def f(l1,r1,l2,r2,top):

  global aaa

  if (l1>r1 or l2>  r2):

    return 0

  if (top-1<=aaa) or (r1-l1+1<=aaa) or (r2-l2+1<=aaa):

    return 0

  if top==2:

    return 1

  if (l1>top):

    l1 -=top

    r1 -= top

  if (l2>top):

    l2-=top

    r2-=top

  #print(l1,r1,l2,r2,top)

  if (l1==l2 and r1==r2):

    return r1-l1+1

  if (l1==0 and r1==top-1):

    return r2-l2+1

  if (l2==0 and r2==top-1):

    return r1-l1+1

  if ( (l1<= l2 and l2<= r1) or (l2<= l1 and l1<= r2)):

    ans =  min(r1,r2) -max(l1,l2)  +1

  else:

    ans = 0

  #print(ans)

  top = top//2

  ans = max(ans, f(l1,min(r1,top-1),l2,min(r2,top-1), top))

  ans = max(ans, f(l1,min(r1,top-1),max(top+1,l2),r2, top))

  ans = max(ans, f(max(l1,top+1),r1, l2,min(r2,top-1), top))

  ans = max(ans, f(max(l1,top+1),r1, max(l2,top+1),r2, top))

  aaa = max(aaa,ans)

  return ans

a = input().split()

print(f(int(a[0]),int(a[1]),int(a[2]),int(a[3]),2**36))

# Made By Mostafa_Khaled


a, b = input().split()
x = int(max(a + b)) + 1
s, v = int(a, x) + int(b, x), 0
while s:
    s, v = s // x, v + 1
print(v)


n, a = [int(x) for x in raw_input().split()]
if a%2:
	print a/2+1
else:
	print (n-a)/2+1


import re
import sys
import time

def read(t=None):
	string = raw_input()
	return string if t is None else [t(x) for x in string.split()]

def solve():
	s, b, e = read(int)
	x, y = read(int)
	p, bus_d = read(int)

	if y <= x:
		#print "--> man faster than bus: ",
		print abs(e-b) * y
		return

	# man should always get on the bus

	man_d = (e-b) / abs(e-b)

	#print "man_d: %2d, bus_d: %2d"%(man_d, bus_d)

	if man_d == 1:
		if bus_d == 1:
			delta = b-p
			if delta < 0:
				delta = s-p+s+b
		else:
			delta = p+b
	else:
		if bus_d == 1:
			delta = s-p + s-b
		else:
			delta = p-b
			if delta < 0:
				delta = p+s+s-b

	walk = 1.0 * (x*delta) / (y-x)
	dist = abs(e-b)

	#print "delta: %f"%delta
	#print "time: %f"%time
	#print "walk: %f"%walk
	#print "dist: %f"%dist

	if walk >= dist:
		#print "--> forget the bus: ",
		print dist * y
		return
	else:
		#print "--> use bus: ",
		#ans = time+(dist-walk)*x
		#print "%g"%ans
		print x * (delta + dist)

if __name__ == "__main__":
	solve()


a, b = map(int, raw_input().split())
if a != b:
	print 1
else:
	print a
	#rs


from math import sqrt
x = int(input())
numbers = [int(i) for i in str(x)]
count = 0
for i in range(1, int(sqrt(x)) + 1):
    if x % i == 0:
        digits = [int(j) for j in str(i)]
        flag = 0
        for j in digits:
            if j in numbers:
                flag = 1
                break
        if flag:
            count += 1
        digits = [int(j) for j in str(x // i)]
        flag = 0
        for j in digits:
            if j in numbers:
                flag = 1
                break
        if flag and x // i != i:
            count += 1
print (count)


n=int(input())
arr=list(map(int,input().split()))
freq=[0]*(101)
for i in arr:freq[i]+=1
maxx=max(freq)
amtOFmaxx=freq.count(maxx)
if amtOFmaxx>=2:print(n)
else:
  must_apper=freq.index(maxx)
  ans=0
  for j in range(1,101):
    if j==must_apper:
      continue
    first_index=[10**6]*(n+1)
    first_index[0]=-1
    curr=0
    for i in range(n):
      if arr[i]==must_apper:
        curr+=1
      elif arr[i]==j:
        curr-=1
      ans=max(ans,i-first_index[curr])
      first_index[curr]=min(first_index[curr],i)
      #print(first_index)
  print(ans)


n = int(raw_input())

def num_ways(make, n):
    if make == 0: return 0
    if make <= n: return (make - 1) / 2
    extra = 2 * n - make + 1
    return extra / 2

target = 0
search = 0
while search < 2 * n:
    target += 1
    search = 10 * search + 9

target -= 1
search /= 10

ans = 0
cur = search
while cur < 2 * n:
    # print 'num ways to make %d using 1..%d is %d' % (cur, n, num_ways(cur, n))
    ans += num_ways(cur, n)
    cur += 10 ** target

print ans


def solve(n, st, k):
    MOD = int(1e9 + 7)
    dp = [0] * (n + 1)
    prefix_sum = [0] * (n + 1)
    dp[st] = 1
    for times in range(k):
        prefix_sum[0] = 0
        for i in range(1, n + 1):
            prefix_sum[i] = prefix_sum[i - 1] + dp[i]
            if prefix_sum[i] >= MOD: prefix_sum[i] -= MOD
        for i in range(1, n + 1):
            t = prefix_sum[n] - prefix_sum[i] + prefix_sum[i - 1] - prefix_sum[i >> 1]
            while t < 0: t += MOD
            while t >= MOD: t -= MOD
            dp[i] = t
    return sum(dp) % MOD

def main():
    n, a, b, k = [int(i) for i in input().split()]
    if a > b:
        print(solve(n - b, a - b, k))
    else:
        print(solve(b - 1, b - a, k))

main()


n, p = map(float, input().split())
ans, n = 0, int(n)
all = n * (n - 1) * (n - 2) // 6

for i in range(n):
    deln, newp = n - i, 0
    if i > 2:
        newp += i * (i - 1) * (i - 2) // 6
    if i > 1:
        newp += deln * i * (i - 1) // 2
    if deln > 1:
        newp += deln * (deln - 1) * i / 4

    if newp / all >= p:
        break
    ans += 1

print(ans)


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

while 1:
    try:
        x, y = map(int, input().split())
    except:
        break

    if gcd(x, y) != 1:
        print('Impossible')
        continue

    res=''
    while x > 0 and y > 0:
        if x > y:
            cnt, give = x // y, 'A'
            x %= y
        else:
            cnt, give = y // x, 'B'
            y %= x
        if x == 0 or y == 0:
            cnt -= 1
        res += str(cnt) + give

    print(res)


s = raw_input()
s = s.split(" ")
vladik = int(s[0])
valera = int(s[1])
c = 1

while True:
    vladik -= c
    c += 1
    valera -= c
    c += 1
    if vladik < 0:
        print "Vladik"
        break
    if valera < 0:
        print "Valera"
        break


a,b,c=map(int,input().split())
M=998244353
def C(x, y):
	z,t=0, 1
	for i in range(min(x,y)+1):
		z+=t
		t*=(x-i)*(y-i)*pow(i+1,M-2,M)%M
	return z
print(C(a,b)*C(a,c)*C(b,c)%M)


A=list(map(int,input().split()))
score=0
for i in range(14):
    score=max(score,sum([j for j in [(A[j] if i!=j else 0)+A[i]//14+(1 if (j+13-i)%14<A[i]%14 else 0) for j in range(14)] if j%2==0]))
print(score)


def go(n,h,v={}):
  if (n,h) not in v:
    v[(n,h)]=(h and sum(go(i,h-1,v)*go(n-1-i,h-1,v) for i in range(n)) or 0) if n else 1
  return v[(n,h)]
n,h=map(int,raw_input().split())
print go(n,n)-go(n,max(0,h-1))


a = input()
b = input()

d = {}
for e in b:
    if e == '9':
        e = '6'
    if e == '5':
        e = '2'
    if e in d:
        d[e] = d[e] + 1
    else:
        d[e] = 1

n = {}
for e in a:
    if e == '9':
        e = '6'
    if e == '5':
        e = '2'
    if e in n:
        n[e] += 1
    else:
        n[e] = 1
result = 10000000
for e in n:
    if e not in d:
        result = 0
        break
    else:
        temp_result = int(d[e] / n[e])
        if temp_result < result:
            result = temp_result

print(result)


n=int(input())
if n==1:
  print(3)
else:
  n-=1
  a,b=n//3,n%3
  ans=4*(a+1)
  if b==1:
    ans+=1
  elif b==2:
    ans+=3
  print(ans)


import sys

sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI1(): return list(map(int1, sys.stdin.buffer.readline().split()))
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
inf = 10**16
# md = 10**9+7
# md = 998244353

n, md = LI()

def nHr(hn, hr):
    return nCr(hn+hr-1, hr-1)

def nPr(com_n, com_r):
    if com_r < 0: return 0
    if com_n < com_r: return 0
    return fac[com_n]*ifac[com_n-com_r]%md

def nCr(com_n, com_r):
    if com_r < 0: return 0
    if com_n < com_r: return 0
    return fac[com_n]*ifac[com_r]%md*ifac[com_n-com_r]%md

n_max = 405
fac = [1]
for i in range(1, n_max+1): fac.append(fac[-1]*i%md)
ifac = [1]*(n_max+1)
ifac[n_max] = pow(fac[n_max], md-2, md)
for i in range(n_max-1, 1, -1): ifac[i] = ifac[i+1]*(i+1)%md
pw = [1]
for i in range(400): pw.append(pw[-1]*2%md)

# dp[i][j]...iにj個目の白を置いたときの場合の数
dp = [[0]*(n//2+2) for _ in range(n+2)]
dp[0][0] = 1
for i in range(1, n+2):
    for j in range(1, n//2+2):
        v = 0
        for k in range(i-2, -1, -1):
            v += dp[k][j-1]*pw[i-k-2]*nCr(i-j, i-k-1)%md
        dp[i][j] = v%md
# p2D(dp)

ans = sum(dp[-1])%md
print(ans)


d={input():0}
for i in range(20,0,-1):
 d,e={},d
 u=10**i/9
 for v,c in e.items():
  for x in range(-6,7):
	t=x*u+v
	if abs(t)<u:d[t]=min(c+i*abs(x),d.get(t,999))
print d[0]


import fractions
t = raw_input()
t = t.split(" ")
a = int(t[0])
b = int(t[1])
l = fractions.gcd(a,b)
a = a/l
b = b/l
if(a==b+1 or b==a+1):
	print "Equal"
elif(a>b):
	print "Masha"
else:
	print "Dasha"


n,m=map(int, raw_input().split(' '))

if n==1 or m==1 or (n==2 or m==2):
	if n==1 or m==1:
        	print n*m
	else:
		if n*m%4!=0:
			print n*m/2+1
		else:
			if  n*m%8==0:
				print n*m/2
			else:
				print (n*m/8+1)*4

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


ar = raw_input().split()
n = int(ar[0])
m = int(ar[1])
k = int(ar[2])
if n%2==0:
	print "Marsel"
else:
	win=False
	i=1
	while i*i<=m:
		if m%i==0:
			if k<=i and i<m:
				win=True
			if k<=m/i and m/i<m:
				win=True
		i+=1
	if win:
		print "Timur"
	else:
		print "Marsel"


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

import sys
import math
import random
import operator
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")

n, p, t = raw_input().split()
n = int(n)
p = float(p)
t = int(t)

def prob(n, k, p):
    """nCk(n, k) * p**k * (1-p)**(n-k)"""
    q = 1 - p
    dec = [p] * k + [q] * (n - k) + [1.0 / x for x in range(1, k + 1)]
    inc = range(n, n - k, -1)

    res = 1.0
    while inc or dec:
        if (res > 1.0 and dec) or not inc:
            res *= dec[-1]
            del dec[-1]
        else:
            res *= inc[-1]
            del inc[-1]

    return res

res = 0.0
if t <= n:
    for x in xrange(1, n + 1):
        res += x * prob(t, x, p)
else:
    for x in xrange(1, n):
        res += x * prob(t, x, p)
    for tlast in xrange(n, t + 1):
        res += n * prob(tlast - 1, n - 1, p) * p
# asda

print res


n = int(input())

board = [[0 for i in range(n + 1)] for j in range(2 * n + 1)]

board[0][0] = 1
for i in range(1, n):
    for j in range(len(board[0])):
        if j > 0:
            board[i][j-1] += board[i-1][j]
        if j + 1 < len(board[0]) and j < 2 * n - i:
            board[i][j+1] += board[i-1][j]
for i in range(n, 2 * n + 1):
    for j in range(len(board[0])):
        if j > 0:
            board[i][j-1] += board[i-1][j]
            #board[i][j-1] %= 1000000007
        if j + 1 < len(board[0]) and j < 2 * n - i:
            board[i][j+1] += board[i-1][j]
            #board[i][j+1] %= 1000000007
ans = 0
for i in range(1, len(board), 2):

    ans += sum(board[i])
    ans %= 1000000007

print(ans)


N = 10 ** 6 * 2
MOD = 1000000007
prime = []
isPrime = [True for i in range(N)]
for i in range(2, N):
    if isPrime[i]:
        prime.append(i)
        for j in range(i * i, N, i):
            isPrime[j] = False
def phi(n):
    ans = 1
    for i in pf(n):
        ans *= pow(i[0],i[1]-1)*(i[0]-1)
    return ans
def pf(n):
    for i in prime:
        cnt = 0
        if n % i == 0:
            while n % i == 0:
                n //= i
                cnt += 1
            yield (i,cnt)
    if n > 1:
        yield (n,1)
n,k = map(int,input().split())
k = (k+1)//2
ans = n
for i in range(k):
    ans = phi(ans)
    if ans == 1:
        break
print(ans % MOD)


MOD = 10 ** 9 + 7

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def combination(n,k,MOD):
    if n < k or k < 0:
        return 0
    ans = 1
    for i in range(n - k + 1, n + 1):
        ans *= i
        ans %= MOD
    for i in range(1,k+1):
        ans *= modinv(i,MOD)
        ans %= MOD
    return ans

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

print(combination(n-1,n-2 * k-1,MOD) * combination(m-1,m - 2 * k - 1,MOD) % MOD)


x = 0
y = 0
nx,ny = map(int,input().split())
if ((nx == 0 or nx == 1) and ny == 0):
    print(0)
else:
    x = 1
    turn = 0
    flag = 0
    while True:
        turn = turn + 1
        while y != x:
            y = y + 1
            if(x == nx and y == ny):
                flag = 1
                break
        if flag == 1:
            break
        k = x * -1
        turn = turn + 1
        while x != k:
            x = x - 1
            if(x == nx and y == ny):
                flag = 1
                break
        if flag == 1:
            break
        turn  = turn + 1
        while y != x:
            y = y - 1
            if(x == nx and y == ny):
                flag = 1
                break
        if flag == 1:
            break
        k = (x * -1) + 1
        turn = turn  + 1
        while x != k:
            x = x + 1
            if(x == nx and y == ny):
                flag = 1
                break
        if flag == 1:
            break
    print(turn)


n=int(input())
curr=list([i for i in range(1,100)])
curr=set(curr)
def isvalid(x):
    if x<1 or x>10**9:
        return 0
    if len(set(str(x)))<=2:
        return 1
cnt=0
while cnt<=10**5 :
    curr1=set()
    for i in curr:
        for j in range(10):
            if isvalid(i*10+j):
                curr1.add(i*10+j)
               # print('hi')
                cnt+=1
    #print(curr1)
    curr|=curr1
curr=sorted(list(curr))
#print(curr)
ans=0
for i in curr:
    if i>=1 and i<=n:
        ans+=1
    elif i>n:
        break
print(ans)


import fileinput

def calc(a, b):
    ans = 0
    l = a + b
    i = 1
    while i <= l:
        P = l // i
        r = l // P
        if P <= a and P <= b:
            an = (a + P) // (P + 1)
            ax = a // P
            bn = (b + P) // (P + 1)
            bx = b // P
            if an <= ax and bn <= bx:
                ans += min(ax + bx, r) - max(an + bn, i) + 1
        i = r + 1
    return ans

if __name__ == '__main__':
    it = fileinput.input()
    a, b = [int(x) for x in next(it).split()]
    print(calc(a, b))


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

a = list(map(int,input().split()))
all_sum = sum(a)
r4,r2 = n,n*2
for v in range(len(a)):
	mid = a[v] // 4
	a[v] = a[v] % 4
	if mid <= r4:
		r4 -= mid
	else:
		a[v] += 4 * (mid - r4)
		r4 = 0
	if r4 == 0:
		break
mid = 0
r22 = 0
for v in a:
	if v % 2 == 1:
		mid += 1
	r22 += v // 2
#print(r4,r22,mid,r2)
if r4 > 0:
	mid -=r4
	r22 -= r4
	if mid < 0:
		r22 -= (mid // -2)
		mid = 0

if r22 + mid > r2:
	print('NO')
else:
	print('YES')


I = lambda : map(int, raw_input().split())

def main():
    mod = 10**9 + 7
    n = input()
    a = I()

    c = [[0]*(n+1) for i in range(n+1)]
    for i in xrange(n+1):
        c[i][0] = c[i][i] = 1
        for j in xrange(1,i):
            c[i][j] = (c[i-1][j-1] + c[i-1][j]) % mod

    dp = [[0]*(n+1) for i in range(11)]

    for i in xrange(a[9],n+1):
        dp[9][i] = 1

    for i in xrange(8,-1,-1):
        for j in xrange(n+1):
            for k in xrange(j-a[i]+1):
                if i > 0:
                    dp[i][j] += dp[i+1][k] * c[j][k]
                elif j > 0 and k > 0:
                    dp[i][j] += dp[i+1][k] * c[j-1][k-1]

    print sum(dp[0][i] for i in xrange(1,n+1)) % mod

if __name__ == '__main__':
    main()


def mirror(x):
    k = 0
    a = x
    while a:
        k += 1
        a //= 10
    s = k * '1'
    return int(s) * 9 - x

l, r = map(int, input().split())
max_p = max(l * mirror(l), r * mirror(r))
for s in range(10):
    n = 5 * 10 ** s
    if l < n < r:
        max_p = max(max_p, n * mirror(n))
print(max_p)


n, c = map(int, input().split())
mod = 10 ** 6 +3
inv = [0, 1]
for i in range(2, max(n, c) + 1):
    inv.append(inv[mod % i] * (mod - mod // i) % mod)
ans = 1
for i in range(1, n + c + 1):
    ans = ans * i % mod
for i in range(1, c + 1):
    ans = ans * inv[i] % mod
for i in range(1, n + 1):
    ans = ans * inv[i] % mod
ans += mod - 1
ans %= mod
print(ans)


MOD = 998244353;import __pypy__;int_add = __pypy__.intop.int_add;int_sub = __pypy__.intop.int_sub;int_mul = __pypy__.intop.int_mul
def make_mod_mul(mod=MOD):
    fmod_inv = 1.0 / mod
    def mod_mul(a, b, c=0):
        res = int_sub(int_add(int_mul(a, b), c), int_mul(mod, int(fmod_inv * a * b + fmod_inv * c)))
        if res >= mod:            return res - mod
        elif res < 0:            return res + mod
        else:            return res
    return mod_mul
mod_mul = make_mod_mul()
def mod_pow(x, y):
    if y == 0:        return 1
    res = 1
    while y > 1:
        if y & 1 == 1:            res = mod_mul(res, x)
        x = mod_mul(x, x);        y >>= 1
    return mod_mul(res, x)
n, m = map(int, input().split());pascal = [[1]]
for _ in range(n + m + 5):
    nl = [1]
    for i in range(_):        nl.append((pascal[-1][i] + pascal[-1][i+1]) % MOD)
    nl.append(1);    pascal.append(nl)
def s1(n,m):
    out = 0
    for row in range(1, n):
        above = row
        below = n - row

        bottom = []
        for i in range(m):
            a = below - 1
            b = i
            a2 = below
            b2 = m-i-1
            bottom.append(mod_mul(pascal[a+b][a] , pascal[a2+b2][a2]))

        top = []
        for i in range(m):
            a = above - 1
            b = i
            a2 = above
            b2 = m-i-1
            top.append(mod_mul(pascal[a+b][a] , pascal[a2+b2][a2]))
        top.reverse()

        curr = 0
        for i in range(m):
            out += mod_mul(curr,bottom[i])
            curr += top[i]
            curr %= MOD
            out %= MOD
    return out * 2

def s2(n,m):
    o = 0
    for i in range(1,n):
        for j in range(1,m):
            a = pascal[i+j-1][i-1]
            b = pascal[n-i+j-1][n-i]
            c = pascal[n-i-1+m-j][m-j]
            d = pascal[i+m-j-1][i]
            #print(a,b,c,d)
            o += mod_mul(mod_mul(a,b),mod_mul(c,d))
    return o

c1 = s1(n,m)
c2 = s1(m,n)
c3 = s2(n,m)

out = (c1 + c2 - 2*c3) % MOD
print(out)


if __name__ == '__main__':
	[a, b, w, x, c] = [int(t) for t in raw_input().strip().split()]
	#print 'a b w x c'
	#print a, b, w, x, c

	k1 = 0
	if b >= x:
		k1 = (b - x) / x + (1 if ((b-x) % x > 0) else 0)
	b -= k1 * x

	if c - k1 <= a:
		print c - a
		exit(0)

	c -= k1

	t = 0
	times_a_red = [0]
	b_start = b

	while True:
		if b < x:
			t += 1
			b = w - (x - b)
		else:
			b = b - x
		times_a_red.append(t)
		if b == b_start:
			break
	#print times_a_red

	lo = 1
	hi = 2**64 - 1
	res = 0
	while lo <= hi:
		mid = lo + (hi - lo) / 2
		_len = len(times_a_red) - 1
		a_decr = mid / _len * times_a_red[-1] + times_a_red[mid % _len]
		if c - mid <= a - a_decr:
			res = mid
			hi = mid - 1
		else:
			lo = mid + 1
	print res + k1
	exit(0)


a, b, m, r0 = map(int, raw_input().split())
nums = {}
i = 0
r = r0
while True:
    r = (a * r + b) % m
    if r in nums:
        print i - nums[r]
        break
    nums[r] = i
    i += 1


__author__ = 'trunghieu11'

def primTable(n):
    prime = [True] * n
    prime[0] = prime[1] = False
    for i in range(2, n):
        if prime[i]:
            j = i * i
            while j < n:
                prime[j] = False
                j += i
    return prime

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

def main():
    p, q = map(int, raw_input().split())
    n = 2000000
    pri = 0
    pal = 0
    isPrime = primTable(n)
    answer = -1
    for i in range(1, n):
        pri += isPrime[i]
        pal += isPalindrome(str(i))
        if pri * q <= pal * p:
            answer = i
    print answer

if __name__ == '__main__':
    main()


x=int(input())
s=input().split()
a=[int(num)for num in s]
q=0
for i in a:
    if i==min(a) and not max(a)==min(a):
        q+=1
if max(a)==min(a):
    print('Bob')
elif x/2<q:
    print('Bob')
else :
    print('Alice')


from sys import stdin

x,y,n,d = [int(x) for x in stdin.readline().split()]
d = d**2

v = []

for vec in range(n):
    v.append([int(x) for x in stdin.readline().split()])

found = {}

def winner(x,y,v,d):
    if x**2 + y**2 > d:
        return 1
    if (x,y) in found:
        return found[(x,y)]
    for a,b in v:
        if winner(x+a,y+b,v,d) == 0:
            found[(x,y)] = 1
            return 1
    found[(x,y)] = 0
    return 0

if winner(x,y,v,d):
    print('Anton')
else:
    print('Dasha')


big = 100010
def gen_mu():
    mu = [1]*big
    mu[0] = 0
    P = [True]*big
    P[0] = P[1] = False
    for i in range(2,big):
        if P[i]:
            j = i
            while j<big:
                P[j] = False
                mu[j] *= -1
                j += i
            j = i*i
            while j<big:
                mu[j] = 0
                j += i*i
    return mu

m = int(input())
mu = gen_mu()

MOD = 10**9+7
def mod_inv(x):
    return pow(x, MOD-2, MOD)

s = 1
for i in range(2,big):
    # p is probabilty that i | a random number [1,m]
    p = (m//i)*mod_inv(m)
    s += (-mu[i])*(p)*mod_inv(1-p)
print(s%MOD)


n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
s = set()
d = dict()
ans = 0

def find():
	max = -1
	maxx = -1
	for i in s:
		if len(d[i]) == 0:
			maxx = i
			max = n + 1
		else:
			if max < d[i][0]:
				max = d[i][0]
				maxx = i
	return maxx

for i in xrange(n + 10):
	d[i] = []

for i,x in enumerate(a):
	d[x].append(i)

for i in a:
	if not i in s:
		ans += 1
		if len(s) >= k:
			x = find()
			s.remove(x)

		s.add(i)
	d[i].pop(0)

print ans


a1, b1, c1 = map(int, input().split())
a2, b2, c2 = map(int, input().split())

if a1 == 0 and b1 == 0 and a2 == 0 and b2 == 0 and c1 != c2:
    print(0)
elif (a1 == 0 and b1 == 0 and c1 == 0) or (a2 == 0 and b2 == 0 and c2 == 0):
    print("-1")
elif (a1 == 0 and b1 == 0 and c1 != 0) or (a2 == 0 and b2 == 0 and c2 != 0) and (c1 == c2):
    print(0)
elif a1*b2 == a2*b1:
    if b2*c1 == c2*b1 and c1*a2 == c2*a1:
        print("-1")
    else:
        print(0)
else:
    print(1)


#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading

#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

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

#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
    def __init__(self, data, default=10**18, func=lambda a, b: min(a,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

class SegmentTree1:
    def __init__(self, data, default=0, func=lambda a, b: a+b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

MOD=10**9+7
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
    p = 2
    c=0
    while (p <= n):

        if (prime[p] == True):
            c+=1
            for i in range(p*p, n+1, p):
                #pp[i]=1
                prime[i] = False
        p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
    def __init__(self, R, C):
        #R * C is the source, and isn't a grid square
        self.par = range(R*C + 1)
        self.rnk = [0] * (R*C + 1)
        self.sz = [1] * (R*C + 1)

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

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

        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

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

    def top(self):
        # Size of component at ephemeral "source" node at index R*C,
        # minus 1 to not count the source itself in the size
        return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
    def __init__(self, _op, _e, _mapping, _composition, _id, v):
        def set(p, x):
            assert 0 <= p < _n
            p += _size
            for i in range(_log, 0, -1):
                _push(p >> i)
            _d[p] = x
            for i in range(1, _log + 1):
                _update(p >> i)

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

        def prod(l, r):
            assert 0 <= l <= r <= _n

            if l == r:
                return _e

            l += _size
            r += _size

            for i in range(_log, 0, -1):
                if ((l >> i) << i) != l:
                    _push(l >> i)
                if ((r >> i) << i) != r:
                    _push(r >> i)

            sml = _e
            smr = _e
            while l < r:
                if l & 1:
                    sml = _op(sml, _d[l])
                    l += 1
                if r & 1:
                    r -= 1
                    smr = _op(_d[r], smr)
                l >>= 1
                r >>= 1

            return _op(sml, smr)

        def apply(l, r, f):
            assert 0 <= l <= r <= _n
            if l == r:
                return

            l += _size
            r += _size

            for i in range(_log, 0, -1):
                if ((l >> i) << i) != l:
                    _push(l >> i)
                if ((r >> i) << i) != r:
                    _push((r - 1) >> i)

            l2 = l
            r2 = r
            while l < r:
                if l & 1:
                    _all_apply(l, f)
                    l += 1
                if r & 1:
                    r -= 1
                    _all_apply(r, f)
                l >>= 1
                r >>= 1
            l = l2
            r = r2

            for i in range(1, _log + 1):
                if ((l >> i) << i) != l:
                    _update(l >> i)
                if ((r >> i) << i) != r:
                    _update((r - 1) >> i)

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

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

        def _push(k):
            _all_apply(2 * k, _lz[k])
            _all_apply(2 * k + 1, _lz[k])
            _lz[k] = _id

        _n = len(v)
        _log = _n.bit_length()
        _size = 1 << _log
        _d = [_e] * (2 * _size)
        _lz = [_id] * _size
        for i in range(_n):
            _d[_size + i] = v[i]
        for i in range(_size - 1, 0, -1):
            _update(i)

        self.set = set
        self.get = get
        self.prod = prod
        self.apply = apply

MIL = 1 << 20

def makeNode(total, count):
    # Pack a pair into a float
    return (total * MIL) + count

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

def getCount(node):
    return node - getTotal(node) * MIL

nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
    return node1 + node2
    # Equivalent to the following:
    return makeNode(
        getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
    )

identityMapping = -1

def mapping(tag, node):
    if tag == identityMapping:
        return node
    # If assigned, new total is the number assigned times count
    count = getCount(node)
    return makeNode(tag * count, count)

def composition(mapping1, mapping2):
    # If assigned multiple times, take first non-identity assignment
    return mapping1 if mapping1 != identityMapping else mapping2

class LazySegUpdate():
    def __init__(self, N):
        self.N = N
        n = 4 * N
        self.tree = [0] * n
        self.lazy = [0] * n

    def queryHelper(self, index, s, e, l, r):
        if self.lazy[index]:
            # Apply lazy to node.
            update = self.lazy[index]
            self.lazy[index] = 0
            self.tree[index] = max(self.tree[index], update)
            # Check if this is leaf.
            if s != e:
                self.lazy[2 * index] = max(self.lazy[2 * index], update)
                self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], update)

        if s > e or s > r or e < l:
            return 0
        if s >= l and e <= r:
            return self.tree[index]
        # Overlapped.
        mid = (s + e) // 2
        return max(self.queryHelper(2 * index, s, mid, l, r), self.queryHelper(2 * index + 1, mid + 1, e, l, r))

    def updateHelper(self, index, s, e, l, r, h):
        if self.lazy[index]:
            # Apply lazy to node.
            update = self.lazy[index]
            self.lazy[index] = 0
            self.tree[index] = max(self.tree[index], update)

            if s != e:
                self.lazy[2 * index] = max(self.lazy[2 * index], update)
                self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], update)

        if s > e or s > r or e < l:
            return
        if s >= l and e <= r:
            self.tree[index] = max(self.tree[index], h)
            if s != e:
                self.lazy[2 * index] = max(self.lazy[2 * index], h)
                self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], h)
            return

        mid = (s + e) // 2
        self.updateHelper(2 * index, s, mid, l, r, h)
        self.updateHelper(2 * index + 1, mid + 1, e, l, r, h)
        self.tree[index] = max(self.tree[2 * index], self.tree[2 * index + 1])

    def query(self, l, r):
        return self.queryHelper(1, 0, self.N - 1, l, r - 1)

    def update(self, l, r, h):
        self.updateHelper(1, 0, self.N - 1, l, r - 1, h)
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
    """memoization decorator for a function taking a single argument"""
    class memodict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret

    return memodict().__getitem__

def pollard_rho(n):
    """returns a random factor of n"""
    if n & 1 == 0:
        return 2
    if n % 3 == 0:
        return 3

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

@memodict
def prime_factors(n):
    """returns a Counter of the prime factorization of n"""
    if n <= 1:
        return Counter()
    f = pollard_rho(n)
    return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
    """returns a list of all distinct factors of n"""
    factors = [1]
    for p, exp in prime_factors(n).items():
        factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
    return factors

def all_factors(n):
    """returns a sorted list of all distinct factors of n"""
    small, large = [], []
    for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
        if not n % i:
            small.append(i)
            large.append(n // i)
    if small[-1] == large[-1]:
        large.pop()
    large.reverse()
    small.extend(large)
    return small
#-----------------------------------Sorted List------------------------------------------
class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

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

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

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

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

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

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

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
    left = 0
    right = n-1
    mid = 0
    res = n
    while (left <= right):
        mid = (right + left)//2
        if (arr[mid] >= key):
            res=mid
            right = mid-1
        else:
            left = mid + 1
    return res

def binarySearch1(arr, n, key):
    left = 0
    right = n-1
    mid = 0
    res=-1
    while (left <= right):
        mid = (right + left)//2
        if (arr[mid] > key):
            right = mid-1
        else:
            res=mid
            left = mid + 1
    return res
#---------------------------------running code------------------------------------------
tt=1
#tt=int(input())
for _ in range (tt):
    #input()
    #n=int(input())
    n,m=map(int,input().split())
    #a=list(map(int,input().split()))
    #b=list(map(int,input().split()))
    #s=input()
    #n=len(s)
    DP=[0]*(n+5)
    CUM=[1]*(n+5)
    CUM[1]=0
    DP[1]=1

    S=1

    for i in range(2,n+1):
        CUM[i]=(CUM[i-1]+CUM[i])%m
        DP[i]=(S+CUM[i])%m
        S+=DP[i]
        S%=m

        for j in range(i+i,n+1,i):
            CUM[j]=(CUM[j]+DP[i]-DP[i-1])%m

    print(DP[n])


"""
T=[[0, 2, 1],
[1, 0, 100],
[1, 2, 0]]
n=5
"""
T=[]
for _ in range(3):
    T.append(map(int,raw_input().split()))
n=int(raw_input())

DP=[[[0 for i in range(3)] for j in range(3)] for k in range(2)]

for i in range(n):
    t=i&1
    for a in range(3):
        for b in range(3):
            if a!=b:
                c=3-a-b
                j=t^1
                #print a,b,c,i,t,j
                DP[j][a][b]=min(DP[t][a][c]+T[a][b]+DP[t][c][b],DP[t][a][b]+T[a][c]+DP[t][b][a]+T[c][b]+DP[t][a][b])

print DP[j][0][2]
exit()


n,k=map(int,input().split())
tuk=n-k
hell=998244353
if(tuk<=0):
	print(0)
	exit(0)
fact=[1]*200005
for i in range(2,200005):
	fact[i]=(i*fact[i-1])%hell
def C(n,r):
	ans=1;
	ans=(fact[r]*fact[n-r])%hell
	ans=(fact[n]*pow(ans,hell-2,hell))%hell
	return ans
ans=C(n,tuk)
if(k!=0):
	ans*=2
res=0
for i in range(tuk):
	t=(C(tuk,i)*pow(tuk-i,n,hell))%hell
	if(i%2):
		res=(res-t+hell)%hell;
	else:
		res=(res+t)%hell;
ans=(ans*res)%hell;
print(ans)


def pos(x):
    global m
    global n
    row=x/m
    column=x%m
    p=[row,column]
    return p
n,m,a,b=(int(i) for i in raw_input().split())
l=pos(a-1)
par=l[0]
pac=l[1]
l=pos(b-1)
pbr=l[0]
pbc=l[1]
if (par==pbr) or ((pac==0) and (pbc==m-1)) or (pac==0 and b==n):
    print 1
elif (pac-pbc==1) or (pac==0) or (pbc==m-1) or (a==1) or (b==n) or (pbr-par==1):
    print 2
else:
    print 3
#print par,pac,pbr,pbc


strLine = input()
listSplit = strLine.split()
d = int(listSplit[0])
L = int(listSplit[1])
v1 = int(listSplit[2])
v2 = int(listSplit[3])
res = (L - d) / (v1 + v2)
print('{0:.6f}'.format(res))


l = [1, 2]
for i in range(1, 100):
    l.append(l[i]+l[i-1])
    if l[-1]>10**18:
        break

l = [0, 0] + l
def perm(n, k):
    if n == 1 and k == 1:
        return [1]
    if n == 2 and k == 1:
        return [1, 2]
    if n == 2 and k == 2:
        return [2, 1]
    if k <= l[n]:
        return [1] + [i+1 for i in perm(n-1, k)]

    return [2, 1] + [i+2 for i in perm(n-2, k - l[n])]

n, k = map(int, input().split(' '))
print(' '.join([str(x) for x in perm(n, k)]))


s=map(int, raw_input().split())
l=s.pop()
ans=((l+1)*(l+2)*(l+3))/6
for i in range(l+1):
    for j in s:
        x = min(j+j-sum(s)+i, l-i)
        if x>=0: ans -= ((x+1)*(x+2))/2
print ans


#!/usr/bin/python

import sys

def Ni(): return tuple(map(int, sys.stdin.readline().split()))

n = Ni()[0]
c = Ni()
c = sorted(c)

F = [0] * (n+1)
for _c in c:
    F[_c] += 1

#print n, c, F
answer = "NO"

def backtrack(stack, avail, sumleft):
    #print stack, avail, sumleft
    if len(stack) == 1 and sumleft == 0:
        print "YES"
        sys.exit(0)

    # shift
    if avail[1] > 0:
        avail[1] -= 1
        #print "shift", i
        backtrack(stack + [1], avail, sumleft - 1)
        avail[1] += 1

    # reduce
    if len(stack) < 2:
        return

    s = 1 + stack[-1]
    for i in range(2, len(stack) + 1):
        s += stack[-i]
        if s >= n + 1:
            break

        if avail[s] > 0:
            avail[s] -= 1
            #print "reduce", s
            backtrack(stack[:-i] + [s], avail, sumleft - s)
            avail[s] += 1

backtrack([], F, sum(c))
print "NO"


from fractions import gcd
b,D=map(int,raw_input().split())
a=200*[0]
z=200*[0]
for d in range(2,101):
	c=0
	t=d
	while gcd(b,t)>1:
		t/=gcd(b,t)
		c+=1
	if t==1:
		a[d]=2
		z[d]=c
		continue
	if b%d==1:
		a[d]=3
		continue
	if (b+1)%d==0:
		a[d]=11
		continue
	a[d]=7
	for i in range(2,d):
		if d%i==0 and gcd(i,d/i)==1 and a[i]!=7 and a[d/i]!=7:
			a[d]=6
print "%d-type"%a[D]
if a[D]==2:
	print z[D]