import sys

n=int(sys.stdin.readline().strip('\n'))
line=sys.stdin.readline().strip('\n').split(' ')
values=map(lambda x:int(x),line)

def evaluateBothSides(start,stop):
    print start,stop
    if stop-start==1:
        return min(values[start-1],values[stop])
    elif stop-start==0:
        return 0
    else:
        maxNum=0
        maxPos=0
        for i in xrange(start,stop):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
        return evaluateBothSides(start,maxPos)+evaluateBothSides(maxPos+1,stop)+min(values[start-1],values[stop])

def evaluateMax(stop):
    2+2

def evaluate(start,stop):
    2+2

def addToQueue(inp,queue):
    out=0
    if inp<queue[-1]:
        queue.append(inp)
    else:
        queue.pop()
        out+=inp
        while inp>queue[-1]:
            out+=queue.pop()
        queue.append(inp)
    return out

def queueEvaluate():
    maxLeft=0
    maxRight=0
    maxPos=0
    maxNum=0
    for i in xrange(0,n):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
    out=0
    queue=[maxNum]
    for i in xrange(maxPos+1,n):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxRight=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    queue=[maxNum]
    for i in xrange(maxPos-1,-1,-1):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxLeft=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    out+=min(maxLeft,maxRight)
    return out

print queueEvaluate()


n = raw_input()
m = raw_input()
lst = [int(x) for x in m.split(' ')]
p = []
ans = 0
for i in range(0, len(lst)):
    p.append(lst[i])
    if i-2 >=0 and lst[i] > lst[i-1] and lst[i-2] > lst[i-1]:
        del(p[-2])
        ans += min(lst[i], lst[i-2])
p.sort()
#print p
for i in range(0, len(p)-2):
    ans += p[i]
print ans


import sys

n=int(sys.stdin.readline().strip('\n'))
line=sys.stdin.readline().strip('\n').split(' ')
values=map(lambda x:int(x),line)

def evaluateBothSides(start,stop):
    print start,stop
    if stop-start==1:
        return min(values[start-1],values[stop])
    elif stop-start==0:
        return 0
    else:
        maxNum=0
        maxPos=0
        for i in xrange(start,stop):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
        return evaluateBothSides(start,maxPos)+evaluateBothSides(maxPos+1,stop)+min(values[start-1],values[stop])

def evaluateMax(stop):
    2+2

def evaluate(start,stop):
    2+2

def addToQueue(inp,queue):
    out=0
    if inp<queue[-1]:
        queue.append(inp)
    else:
        queue.pop()
        out+=inp
        while inp>queue[-1]:
            out+=queue.pop()
        queue.append(inp)
    return out

def queueEvaluate():
    maxLeft=0
    maxRight=0
    maxPos=0
    maxNum=0
    for i in xrange(0,n):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
    out=0
    queue=[maxNum]
    for i in xrange(maxPos+1,n):
        out+=addToQueue(values[i],queue)
    if len(queue)==1:
        pass
    else:
        maxRight=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    queue=[maxNum]
    for i in xrange(maxPos-1,-1,-1):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxLeft=queue[i]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    out+=min(maxLeft,maxRight)
    return out

print queueEvaluate()


import sys

n=int(sys.stdin.readline().strip('\n'))
line=sys.stdin.readline().strip('\n').split(' ')
values=map(lambda x:int(x),line)

def evaluateBothSides(start,stop):
    print start,stop
    if stop-start==1:
        return min(values[start-1],values[stop])
    elif stop-start==0:
        return 0
    else:
        maxNum=0
        maxPos=0
        for i in xrange(start,stop):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
        return evaluateBothSides(start,maxPos)+evaluateBothSides(maxPos+1,stop)+min(values[start-1],values[stop])

def evaluateMax(stop):
    2+2

def evaluate(start,stop):
    2+2

def addToQueue(inp,queue):
    out=0
    if inp<queue[-1]:
        queue.append(inp)
    else:
        queue.pop()
        out+=inp
        while inp>queue[-1]:
            out+=queue.pop()
        queue.append(inp)
    return out

def queueEvaluate():
    maxLeft=0
    maxRight=0
    maxPos=0
    maxNum=0
    for i in xrange(0,n):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
    out=0
    queue=[maxNum]
    for i in xrange(maxPos+1,n):
        out+=addToQueue(values[i],queue)
        print queue
    if len(queue)==1:
        pass
    else:
        maxRight=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    queue=[maxNum]
    for i in xrange(maxPos-1,-1,-1):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxLeft=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    out+=min(maxLeft,maxRight)
    return out

print queueEvaluate()


n = raw_input()
m = raw_input()
lst = [int(x) for x in m.split(' ')]
p = []
for i in range(1, len(lst)-1):
    p.append(min(lst[i-1], lst[i+1]))
ans = 0
while len(p) > 0:
    id = p.index(max(p))
    ans += max(p)
    if id-1 >= 0 and id+2 < len(lst):
        p[id-1] = min(lst[id-1], lst[id+2])
    if id+1 < len(p) and id+3 < len(lst):
        p[id+1] = min(lst[id], lst[id+3])
    del(p[id])
    del(lst[id+1])
print ans


import math

def field(n, x, y, t):
    t = t + 1
    upper_dist = x - 1
    left_dist = y - 1
    down_dist = n - x
    right_dist = n - y
    out_up = max(0, t - upper_dist - 1)
    out_down = max(0, t - down_dist - 1)
    out_left = max(0, t - left_dist - 1)
    out_right = max(0, t - right_dist - 1)
    #print(out_up, out_right, out_down, out_left)
    #print(base_field(t), right_field(out_right), right_field(out_left), up_field(out_up, n, y), up_field(out_down, n, y))
    field = base_field(t) - right_field(out_right) - right_field(out_left) - up_field(out_up, n, y) - up_field(out_down, n, y)
    return field

def right_field(out_r):
    return out_r ** 2

def up_field(out_up, n, y):
    rect = max(0, out_up - n + 1)
    h = out_up - rect
    wyst = max(y - 1 + h - n, 0, h - y)
    result = n * rect + h ** 2 - int((1 + wyst) / 2 * wyst)
    if result < 0:
        result = 0
    return result

def base_field(t):
    return 2 * (t ** 2) - 2 * t + 1

class CodeforcesTask256BSolution:
    def __init__(self):
        self.result = ''
        self.n_x_y_c = []

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

    def process_task(self):
        search = 0
        mid = 1
        found = False
        last_sm = 0
        while not found:
            #print(last_sm ,search)
            ff = field(self.n_x_y_c[0], self.n_x_y_c[1], self.n_x_y_c[2], search)
            if ff == self.n_x_y_c[3]:
                found = True
            elif ff > self.n_x_y_c[3]:
                if search - last_sm == 1:
                    found = True
                else:
                    search = last_sm + (search - last_sm) // 2
            else:
                last_sm = search
                search += mid
                mid = search - last_sm
        self.result = str(search)

    def get_result(self):
        return self.result

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


#http://codeforces.ru/problemset/problem/255/D

def cells_dir(second):
    return sum(xrange(1,second*2,2))

def doubles(second, x, y, n):
    d = 0
    corners = [x+n-y+1, y+n-x+1, x+y, (n-x+1) + (n-y+1)]
    for corner in corners:
        if corner <= second:
            d += sum(xrange(1, second - corner + 2))
    return d

def cells_a(second, x, y, n):
    dcx = cells_dir(second-x+1) + cells_dir(second-n+x)
    dcy = cells_dir(second-y+1) + cells_dir(second-n+y) - doubles(second, x, y, n)
    return (sum(xrange(1,second*2,2))*2 + second*2 + 1)- dcx - dcy

n, x, y, c = map(int, raw_input().split())
second = 0
while cells_a(second, x, y, n) < c:
    second += 1000
high = second
low = second - 1000 if second !=0 else 0
second = 0

##if c == n**2

while high - low > 1:
    second = (high + low) / 2
    cells = cells_a(second, x, y, n)
    if  cells > c:
        high = second
    elif cells < c:
        low = second
    elif cells == n**2:
        high = second
    else:
        break
else:
    if cells_a(low, x, y, n) > c:
        second = low
    else:
        second = high

print second


def g(v):
	return 0 if v < 0 else v * v

def h(v):
	return 0 if v < 0 else v * (v + 1) / 2

def f(v):
	return g(v + 1) + g(v) - g(v + 1 - x) - g(v + 1 - n - 1 + x) - g(v + 1 - y) - g(v + 1 - n - 1 + y) + h(v + 1 - x - y) + h(v + 1 - n - 1 + x - y) + h(v + 1 - x - n - 1 + y) + h(v + 1 - n - 1 + x - n - 1 + y)

n, x, y, c = map(int, raw_input().split())
l = 0
r = c
while l <= r:
	v = (l + r) / 2
	if f(v) < c:
		l = v + 1
	else:
		r = v - 1
		p = v
print p


import sys

def switchOn(switchedOn, points):
    for (x,y) in points:
        if (x,y) not in switchedOn:
            switchedOn.add((x,y))

def getNeighbors(x,y):
    neighbors = []
    if x!=n:
        neighbors.append((x+1,y))
    if y!=n:
        neighbors.append((x,y+1))
    if x!=1:
        neighbors.append((x-1,y))
    if y!=1:
        neighbors.append((x,y-1))
    return neighbors

def expand(points,i,switchedOn,c):
    switchOn(switchedOn, points)
    if len(switchedOn) >= c:
        print i
        sys.exit()
    else:
        allNeighbors = []
        for (x,y) in points:
            neighbors = getNeighbors(x,y)
            allNeighbors.extend(neighbors)
        expand(allNeighbors,i+1,switchedOn,c)

if __name__ == '__main__':
    n,x,y,c = map(int,raw_input().split())
    if c == 1:
        print 0
    else:
        switchedOn = set()
        points = [(x,y)]
        expand(points,0,switchedOn,c)


import sys

def sum(i):
    if i%2 == 0:
        return (i+1)*(i/2)
    else:
        return (i+1)*((i-1)/2)+((i+1)/2)

def switched(i,m,k):
    if i <= min(m,k):
        return sum(i)
    elif i>min(m,k) and i<max(m,k):
        return sum(min(m,k)) + (min(m,k)*(i-min(m,k)))
    elif i>=max(m,k) and i < max(m,k)+min(m,k):
        tmp = i - max(m,k)+1
        return sum(min(m,k)) + (min(m,k)*(max(m,k)-min(m,k)-1)) + sum(min(m,k))-sum(min(m,k)-tmp)
    else:
        return m*k

if __name__ == '__main__':
    n,x,y,c = map(int,raw_input().split())
    if c == 1:
        print 0
    else:
        i=1
        num = 1
        while num < c:
            num = switched(i,x,y-1) + switched(i,n-x,y) + switched(i,n-x+1,n-y) + switched(i,x-1,n-y+1)
            i = i + 1
        print i - 1


def F (x) :
    if (x < 10) :
        return x

    rv = 9
    tmp = x
    len = 0
    while (tmp > 0) :
        len += 1
        tmp /= 10

    d = int (x / pow(10, len-1))

    tmp = 1
    for i in range(len - 2) :
        rv += 9 * tmp
        tmp *= 10

    for i in range (1, 10) :
        if (i < d) :
            rv += 1 * tmp

    if (x / (pow(10, len-1)) <= x % 10) :
        rv += 1

    rv += (x % (pow(10, len - 1))) / 10

    return rv
}

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

print(F(r) - F(l-1))

#     author: Ashwin Ginoria
#     email: ashwinginoria@gmail.com
#  123456789012345678
# 100000000000000000
# 1000000000000000000


//============================================================================
// Name        : A.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
long long dp[20][12];
int bit[20];
long long dfs(int pos,int pre1,int pre2,bool flag,bool z)
{
    if(pos==-1)return pre1==pre2;
    if(pre1!=0 && !flag &&dp[pos][pre1]!=-1)
        return dp[pos][pre1];
    long long ans=0;
    int end=flag?bit[pos]:9;
    for(int i=0;i<=end;i++)
    {
        ans+=dfs(pos-1,(z)?i:pre1,i,flag && i==end,z&&(i==0));
    }
    if(!flag &&pre1!=0)dp[pos][pre1]=ans;
    return ans;
}
long long calc(long long n)
{
    int len=0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    return dfs(len-1,0,0,1,1);
}
int main()
{
    long long l,r;
    memset(dp,-1,sizeof(dp));
    while(scanf("%I64d%I64d",&l,&r)==2)
    {
        printf("%I64d\n",calc(r)-calc(l-1));
    }
    return 0;
}


n=input().split()
l=int(n[0])
r=int(n[1])
s=0
for i in range(l,r):
    i=str(i)
    if i[0]==i[len(i)-1]:
        s+=1
print(s)


n = int(input())
s = input()
dp = [[None for i in range(n + 1)] for i in range(n + 1)]
dp[0][0] = ('', '0', '0')
for i in range(1, n * 2 + 1):
    for j in range(max(0, i - n), min(i, n) + 1):
        k = i - j
        curr = 0
        if j > 0:
            choices, h, m = dp[j - 1][k]
            choices += 'H'
            if len(h) < j:
                h += s[i - 1]
            else:
                tmp = [c for c in h]
                tmp[j - 1] = s[i - 1]
                h = ''.join(tmp)
            if len(m) < j:
                m += '0'
            sum = int(h) + int(m)
            if sum > curr:
                curr = sum
                dp[j][k] = (choices, h, m)
        if k > 0:
            choices, h, m = dp[j][k - 1]
            choices += 'M'
            if len(m) < k:
                m += s[i - 1]
            else:
                tmp = [c for c in m]
                tmp[k - 1] = s[i - 1]
                m = ''.join(tmp)
            if len(h) < k:
                h += '0'
            sum = int(h) + int(m)
            if sum > curr:
                curr = sum
                dp[j][k] = (choices, h, m)
print(dp[n][n][0])


def solve(n_homer=0, n_medea=0):
    global number, n

    if (n_homer, n_medea) in mem:
		return mem[n_homer, n_medea][0]

    best = [0, 0]
    pos = n_homer + n_medea

    if n_homer < n:
        aux = solve(n_homer + 1, n_medea)[:]
        aux[0] = int(number[pos] + str(aux[0]))
        if sum(best) < sum(aux):
			mem[n_homer, n_medea] = aux[:], 'H'
			best = aux[:]

    if n_medea < n:
        aux = solve(n_homer, n_medea + 1)[:]
        aux[1] = int(number[pos] + str(aux[1]))
        if sum(best) < sum(aux):
			mem[n_homer, n_medea] = aux[:], 'M'
			best = aux[:]

    return best[:]

mem = {}
n = input()
number = raw_input()

# print solve()

solution = ""
n_homer, n_medea = 0, 0

while n_homer < n or n_medea < n:
	if mem[n_homer, n_medea][1] == 'H':
		n_homer += 1
		solution += 'H'
	else:
		n_medea += 1
		solution += 'M'

print solution


def val(pair):
	s = 0
	if pair[0] != '':
		s += int(pair[0])
	if pair[1] != '':
		s += int(pair[1])
	return s

def solve(n_homer=0, n_medea=0):
    global number, n

    if (n_homer, n_medea) in mem:
		return mem[n_homer, n_medea][0]

    best = ['', '']
    best_c = 'Crap'
    pos = n_homer + n_medea

    if n_homer < n:
        best = solve(n_homer + 1, n_medea)[:]
        best[0] = number[pos] + str(best[0])
        best_c = 'H'

    if n_medea < n:
        aux = solve(n_homer, n_medea + 1)[:]
        aux[1] = number[pos] + str(aux[1])
        if val(best) < val(aux):
			best = aux
			best_c = 'M'

	mem[n_homer, n_medea] = best, best_c

    return best

mem = {}
n = input()
number = raw_input()

solve()

# for k in sorted(mem.keys()):
#     print k, mem[k]

solution = ""
n_homer, n_medea = 0, 0

while n_homer < n or n_medea < n:
	# print solution
	if mem[n_homer, n_medea][1] == 'H':
		n_homer += 1
		solution += 'H'
	else:
		n_medea += 1
		solution += 'M'

print solution


def val(pair):
	s = 0
	if pair[0] != '':
		s += int(pair[0])
	if pair[1] != '':
		s += int(pair[1])
	return s

def solve(n_homer=0, n_medea=0):
    global number, n

    if (n_homer, n_medea) in mem:
		return mem[n_homer, n_medea][0]

    best = ['', '']
    pos = n_homer + n_medea

    if n_homer < n:
        best = solve(n_homer + 1, n_medea)[:]
        best[0] = number[pos] + str(best[0])
        mem[n_homer, n_medea] = best, 'H'

    if n_medea < n:
        aux = solve(n_homer, n_medea + 1)[:]
        aux[1] = number[pos] + str(aux[1])
        if val(best) < val(aux):
			best = aux
			mem[n_homer, n_medea] = best, 'M'

    return best

mem = {}
n = input()
number = raw_input()

solve()

# for k in sorted(mem.keys()):
#     print k, mem[k]

solution = ""
n_homer, n_medea = 0, 0

while n_homer < n or n_medea < n:
	# print solution
	if mem[n_homer, n_medea][1] == 'H':
		n_homer += 1
		solution += 'H'
	else:
		n_medea += 1
		solution += 'M'

print solution


n = int(raw_input())
s = raw_input()
global p, q, ans
p = [[0 for i in range(n+1)] for j in range(n+1)]
q = [[0 for i in range(n+1)] for j in range(n+1)]

def f(a, b):
	global p, q
	if p[a][b] != 0:
		return p[a][b]
	if a > 0:
		y = f(a-1, b) + (10**(a-1))*int(s[n*2-a-b])
		if p[a][b] <= y:
			p[a][b] = y
			q[a][b] = 'M'
	if b > 0:
		y = f(a, b-1) + (10**(b-1))*int(s[n*2-a-b])
		if p[a][b] <= y:
			p[a][b] = y
			q[a][b] = 'H'
	return p[a][b]
def g(a, b):
	global q, ans
	if q[a][b] != 0:
		ans += q[a][b]
	if q[a][b] == 'M':
		g(a-1, b)
	if q[a][b] == 'H':
		g(a, b-1)

ans = ''
f(n, n)
g(n, n)
print ans


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

s = input() + '+'
r = 0
a = 0
z = '+'
for i in s:
    #print(r, a, z)
    if i in '+-':
        if z == '+':
            r += a
        else:
            r -= a
        z = i
        a = 0
    a *= 10
    a += ord(i) - ord('0')

print(r)


s = input()
val = eval(s)
for i in range(len(s)):
    if s[i] ==  '+':
        j = i + 1
        c = -5
        while j < len(s) and s[j] != '+' and s[j] != '-':
            c *= 10
            j += 1
        val += c
    elif s[i] == '-':
        j = i + 1
        c = 3
        while j < len(s) and s[j] != '+' and s[j] != '-':
            c *= 10
            j += 1
        val += c
print(val)


a = input()
q, s = [0], 0
z = []
for i in range(len(a)):
    y = a[i]
    if (y=="+"):
        z.append(1)
        q.append(0)
        s+=1
    elif (y=="-"):
        z.append(-1)
        q.append(0)
        s+=1
    q[s] = 10*q[s] + (ord(y)-ord("0"))
otv = q[0]
for i in range(1, s+1):
    otv += z[i-1]*q[i]
print(otv)


s = input()
now = 0
n = len(s)
ans = []
while (now < n) and (s[now] != '-') and (s[now] != '+'):
    ans.append(ord(s[now])-48)
    now += 1
ans.reverse()
while now < n:
    opt = s[now]
    now += 1
    a = [opt]
    while (now < n) and (s[now] != '-') and (s[now] != '+'):
        a.append(ord(s[now])-48)
        now += 1
    a.reverse()
    if len(a) <= len(ans):
        for i in range(len(ans) - len(a)):
            a.append(0)
    else:
        for i in range(len(a) - len(ans)):
            ans.append(0)
    for i in range(len(ans)):
        if opt == '-':
            ans[i] -= ord(s[now - 1 - i])-48
        else:
            ans[i] += ord(s[now - 1 - i])-48
ret = 0
ans.reverse()
for i in range(len(ans)):
    ret = ret * 10 + ans[i]
print(ret)


es (14 sloc)  248 Bytes
s = input().strip() + '+'
ans = 0

curr = 0
sign = 1
for c in s:
    if c in '-+':
        ans += sign*curr
        curr = 0
    if c == '-':
        sign = -1
    elif c == '+':
        sign = 1
    curr = curr*10 + (ord(c) - ord('0'))
print(ans)


#!/usr/bin/env python3
# 604D_modular.py - Codeforces.com/problemset/problem/604/D by Sergey 2015

import unittest
import sys

###############################################################################
# Modular Class (Main Program)
###############################################################################

class Binominals:
    """ Binominals representation """

    def mod(self, a):
        return a % self.m

    def add(self, a, b):
        return (a + b) % self.m

    def mul(self, a, b):
        return (a * b) % self.m

    def pow(self, e, n):
        r = 1
        while n > 0:
            if n & 1:
                r = self.mul(r, e)
            e = self.mul(e, e)
            n >>= 1
        return r

    def inv(self, a):
        return self.pow(a, self.m-2)

    def __init__(self, mod=(10**9)+7, maxn=10**5):
        self.m = mod

class Modular:
    """ Modular representation """

    def __init__(self, test_inputs=None):
        """ Default constructor """

        it = iter(test_inputs.split("\n")) if test_inputs else None

        def uinput():
            return next(it) if it else sys.stdin.readline().rstrip()

        # Reading single elements
        [self.p, self.k] = map(int, uinput().split())

        self.M = 10**9+7

    def calculate(self):
        """ Main calcualtion function of the class """

        result = 0
        bp = Binominals(mod=self.p)
        for m in range(1, self.p):
            if bp.pow(self.k, m) == 1:
                break

        bb = Binominals(mod=self.M)
        if self.k == 0:
            result = bb.pow(self.p, self.p-1)
        elif self.k == 1:
            result = bb.pow(self.p, self.p)
        else:
            result = bb.pow(self.p, (self.p-1)//m)

        return str(result)

###############################################################################
# Unit Tests
###############################################################################

class unitTests(unittest.TestCase):

    def test_single_test(self):
        """ Modular class testing """

        # Constructor test
        test = "3 2"
        d = Modular(test)
        self.assertEqual(d.k, 2)
        self.assertEqual(d.p, 3)

        # Sample test
        self.assertEqual(Modular(test).calculate(), "3")

        # Sample test
        test = "5 4"
        self.assertEqual(Modular(test).calculate(), "25")

        # Sample test
        test = "5 0"
        self.assertEqual(Modular(test).calculate(), "625")

        # My tests
        test = ""
        # self.assertEqual(Modular(test).calculate(), "0")

        # Time limit test
        # self.time_limit_test(5000)

    def time_limit_test(self, nmax):
        """ Timelimit testing """
        import random
        import timeit

        # Random inputs
        test = str(nmax) + " " + str(nmax) + "\n"
        numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
        test += "\n".join(numnums) + "\n"
        nums = [random.randint(1, 10000) for i in range(nmax)]
        test += " ".join(map(str, nums)) + "\n"

        # Run the test
        start = timeit.default_timer()
        d = Modular(test)
        calc = timeit.default_timer()
        d.calculate()
        stop = timeit.default_timer()
        print("\nTimelimit Test: " +
              "{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
              format(stop-start, calc-start, stop-calc))

if __name__ == "__main__":

    # Avoiding recursion limitaions
    sys.setrecursionlimit(100000)

    if sys.argv[-1] == "-ut":
        unittest.main(argv=[" "])

    # Print the result string
    sys.stdout.write(Modular().calculate())


from sys import stdin

p, k = stdin.readline().rstrip().split(' ')
p = int(p); k = int(k)

if k==0:
	print(((p)**(p-1)) % (10**9+7))

elif k==1:
	print((p**p) % (10**9+7))

else:
	free = set(range(1, p))
	loops = 0

	while free:
		n = free.pop()
		l = (n*k)%p
		while l != n:
			free.remove(l)
			l = (l*k) % p
		loops += 1

	print(p**loops % (10**9+7))


(p, k) = map(int, input().split())
used = [0] * p
if k == 0:
    print(pow(p, p - 1) % (10 ** 9 + 7))
else:
    c = 1 if k == 1 else 0
    for x in range(1, p):
        if not used[x]:
            y = x
            while not used[y]:
                used[y] = True
                y = k * y % p
            c += 1
    print(pow(p, c) % (10 ** 9 + 7))


p,k = map(int,raw_input().split())
M = 1000000007

if k == 0:
    print pow(p, p-1, M)
elif k == 1:
    print pow(p, p, M)
else:
    m = 1
    for i in range(1,p+1):
        if pow(k, i, p) == 1:
            m = i
            break
    print pow(p, (p-1)/m, M)


from sys import stdin
n,k=map(int,stdin.readline().strip().split())
pairs=(n-1)//2
mod=10**9+7
if k==0 of k==1:
    print(pow(n,n,mod))
    exit(0)
print(pow(n,pairs,mod))


n = int(input())
*a, = map(int, input().split())
b = sorted(a)
for i in a:
    print((a[b.index(i) + 1) % n], end=' ')


n,a =int(input()),map(list(int,input().split()))
b =sorted(a) + [min(a)]
print(' '.join([str(b[b.index(a[ i ])+1] for i in range(n)]))


n,a =int(input()),map(list(int,input().split()))
b =sorted(a) + [min(a)]
print(''.join([str(b[b.index(a[ i ])+1] for i in range(n)]))


n = int(input())
*a, = map(int, input().split())
b = sorted(a)
for i in a:
    print((a[b.index(i) + 1]) % n], end=' ')


n,a =int(input()),map(list(int,input().split()))b
b =sorted(a) + [min(a)]
print(''.join([str(b[b.index(a[ i ])+1] for i in range(n)]))


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 10/10/18

"""

import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

C = [
    ['#', '#', '#'],
    ['#', '', '#'],
    ['#', '#', '#'],
]

N, M = map(int, input().split())

res = [['.' for _ in range(M)] for _ in range(N)]

A = []
for i in range(N):
    A.append([x for x in input()])

for i in range(N - 2):
    for j in range(M - 2):
        if A[i][j] != '#':
            continue

        edge = []
        for x in range(3):
            for y in range(3):
                if not (x == 1 and y == 1):
                    edge.append((i + x, j + y))

        if all(A[r][c] == '#' for (r, c) in edge):
            for r, c in edge:
                res[r][c] = '#'
#
# for row in res:
#     print(''.join(row))

if res == A:
    print('YES')
else:
    print('NO')


n,m=map(int,input().split())
a=[[*input()]for _ in[0]*n]
p=0,1,2
p=[*zip((0,0,0,1,1,2,2,2),p+(0,)+p]
for i in range(n-2):
 for j in range(m-2):
  if all(a[i+k][j+l]<'.'for k,l in p):
   for k,l in p:a[i+k][j+l]='$'
print('YNEOS'[any('#'in x for x in a)::2])


def Mir(x, c): return c * 2 - x

def Solve(A):
    A[0].sort()
    A[1].sort()
    I0, I1 = 0, 1
    if A[0][-1] - A[0][0] > A[1][-1] - A[1][0]: I0, I1 = I1, I0
    if A[I1][-1] == A[I1][0]:
        if A[I1][0] == A[I0][0]: return []
        return None
    elif A[I0][-1] == A[I0][0]:
        return None

    ops = [[], []]
    def Op(I, J1, JC):
        ops[I].append((A[I0][J1], A[I0][JC]))
        A[I0][J1] = Mir(A[I0][J1], A[I0][JC])
    while True:
        for a in A: a.sort()
        if max(A[0][-1], A[1][-1]) - min(A[0][0], A[1][0]) <= 1: break
        gapL = abs(A[0][0] - A[1][0])
        gapR = abs(A[0][-1] - A[1][-1])
        if gapL > gapR:
            I0, I1 = (0, 1) if A[0][0] < A[1][0] else (1, 0)
            view = lambda x: x
        else:
            I0, I1 = (0, 1) if A[0][-1] > A[1][-1] else (1, 0)
            view = lambda x: 3 - x
        for a in A: a.sort(key=view)
        lim = max(view(A[I0][-1]), view(A[I1][-1]))
        B = [view(x) for x in A[I0]]

        actioned = False
        for J in (3, 2):
            if Mir(B[0], B[J]) <= lim:
                Op(I0, (0), (J))
                actioned = True
                break
        if actioned: continue

        if Mir(B[0], B[1]) > lim:
            Op(I0, (3), (1))
            continue
        if (B[1] - B[0]) * 8 >= lim - B[0]:
            Op(I0, (0), (1))
            continue
        if (B[3] - B[2]) * 8 >= lim - B[0]:
            Op(I0, (0), (2))
            Op(I0, (0), (3))
            continue
        if B[1] - B[0] < B[3] - B[2]:
            Op(I0, (1), (2))
            Op(I0, (1), (3))
        else:
            Op(I0, (2), (1))
            Op(I0, (2), (0))
        Op(I0, (0), (1))
    if A[0] != A[1]: return None
    return ops[0] + [(Mir(x, c), c) for x, c in reversed(ops[1])]

def Output(ops):
    if ops is None:
        print(-1)
        return
    print(len(ops))
    for x, c in ops: print(x, c)

import sys
A = [list(map(int, sys.stdin.readline().split())) for _ in range(2)]
Output(Solve(A))


from math import sin
def mp():  return map(int,input().split())
def lt():  return list(map(int,input().split()))
def pt(x):  print(x)
def ip():  return input()
def it():  return int(input())
def sl(x):  return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x):  return "{0:b}".format(x)
def listring(l): return ' '.join([str(x) for x in l])
def ptlist(l): print(' '.join([str(x) for x in l]))

n = it()
step = lt()
dict = {}
def explosion(start,s,d):
    (i,j) = start
    t = s+1
    if d == 0:
        for k in range(j+1,j+t):
            dict[(i,k)] = True
        return ((i,j+t-1),(d+7)%8),((i,j+t-1),(d+1)%8)
    if d == 1:
        for k in range(1,t):
            dict[(i+k,j+k)] = True
        return ((i+t-1,j+t-1),(d+7)%8),((i+t-1,j+t-1),(d+1)%8)
    if d == 2:
        for k in range(1,t):
            dict[(i+k,j)] = True
        return ((i+t-1,j),(d+7)%8),((i+t-1,j),(d+1)%8)
    if d == 3:
        for k in range(1,t):
            dict[(i+k,j-k)] = True
        return ((i+t-1,j-t+1),(d+7)%8),((i+t-1,j-t+1),(d+1)%8)
    if d == 4:
        for k in range(1,t):
            dict[(i,j-k)] = True
        return ((i,j-t+1),(d+7)%8),((i,j-t+1),(d+1)%8)
    if d == 5:
        for k in range(1,t):
            dict[(i-k,j-k)] = True
        return ((i-t+1,j-t+1),(d+7)%8),((i-t+1,j-t+1),(d+1)%8)
    if d == 6:
        for k in range(1,t):
            dict[(i-k,j)] = True
        return ((i-t+1,j),(d+7)%8),((i-t+1,j),(d+1)%8)
    if d == 7:
        for k in range(1,t):
            dict[(i-k,j+k)] = True
        return ((i-t+1,j+t-1),(d+7)%8),((i-t+1,j+t-1),(d+1)%8)

start = [((0,0),0)]
for i in range(n):
    l = []
    for p,q in start:
        a,b = explosion(p,step[i],q)
        l.append(a)
        l.append(b)
    start = list(l)
pt(len(dict))


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

n = int(input())
t = [int(i) for i in input().split()]

def dfs(d, pos, path):
    if d == n+1:
        return set()
    cell = set()
    c = t[d-1]
    for _ in range(c):
        pos = (pos[0] + dr[path][0], pos[1] + dr[path][1])
        cell.add(pos)
    cell = cell.union(dfs(d+1, pos, (path+1) % 8))
    cell = cell.union(dfs(d+1, pos, (path-1) % 8))
    return cell

total_cells = dfs(1, (0, 0), 0)
print(len(total_cells))


#   N
# W  E
#  S

def go(x,y,cur_fac,t_idx,cells,tlist):
    if t_idx >= len(tlist):
        return None

    cells[x][y] = 1

    if cur_fac == "N":
        steps = tlist[t_idx]
        for i in range(steps-1):
            y+=1
            cells[x][y] = 1
        go(x-1,y+1,"NW",t_idx+1,cells,tlist)
        go(x+1,y+1,"NE",t_idx+1,cells,tlist)

    if cur_fac == "NW":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            y+=1
            cells[x][y] = 1
        go(x-1,y,"W",t_idx+1,cells,tlist)
        go(x,y+1,"N",t_idx+1,cells,tlist)

    if cur_fac == "W":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            cells[x][y] = 1
        go(x-1,y+1,"NW",t_idx+1,cells,tlist)
        go(x-1,y-1,"SW",t_idx+1,cells,tlist)

    if cur_fac == "SW":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x-=1
            y-=1
            cells[x][y] = 1
        go(x-1,y,"W",t_idx+1,cells,tlist)
        go(x,y-1,"S",t_idx+1,cells,tlist)

    if cur_fac == "S":
        steps = tlist[t_idx]
        for i in range(steps-1):
            y-=1
            cells[x][y] = 1
        go(x-1,y-1,"SW",t_idx+1,cells,tlist)
        go(x+1,y-1,"SE",t_idx+1,cells,tlist)

    if cur_fac == "SE":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            y-=1
            cells[x][y] = 1
        go(x,y-1,"S",t_idx+1,cells,tlist)
        go(x+1,y,"E",t_idx+1,cells,tlist)

    if cur_fac == "E":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            cells[x][y] = 1
        go(x+1,y+1,"NE",t_idx+1,cells,tlist)
        go(x+1,y-1,"SE",t_idx+1,cells,tlist)

    if cur_fac == "NE":
        steps = tlist[t_idx]
        for i in range(steps-1):
            x+=1
            y+=1
            cells[x][y] = 1
        go(x,y+1,"N",t_idx+1,cells,tlist)
        go(x+1,y,"E",t_idx+1,cells,tlist)

d = input()
tlist = map(int,raw_input().strip().split())
dim = 2*sum(tlist)+2
cells = [[0 for i in range(dim)] for i in range(dim)]
go(dim/2, dim/2, "N", 0, cells, tlist)
s = 0
for row in cells[::-1]:
    #print " ".join([str(i) for i in row])
    s += sum(row)
print s


from enum import Enum
from queue import Queue
from collections import deque

class  Dir(Enum):
    N = 1
    E = 2
    S = 3
    W = 4
    NE = 5
    SE = 6
    SW = 7
    NW = 8

if __name__ == "__main__":

    dirdict = {
                Dir.N : (Dir.NE, Dir.NW),
                Dir.S : (Dir.SE, Dir.SW),
                Dir.W : (Dir.SW, Dir.NW),
                Dir.E: (Dir.NE, Dir.SE),
                Dir.NE : (Dir.N, Dir.E),
                Dir.SE : (Dir.E, Dir.S),
                Dir.SW : (Dir.S, Dir.W),
                Dir.NW: (Dir.N, Dir.W)}

    n=int(input().strip())
    lst = list(map(int, input().strip().split()))

    result=[[False for _ in range(400)]  for _ in range(400)]
    q=deque()
    a=((200,200), Dir.N,0)
    q.append(a)

    while len(q) > 0:
        position,direction,stage=q.pop()
        if stage == len(lst):
            continue
        else:
            (x,y) = position
            if direction == Dir.N:
                for j in range(1,lst[stage]+1):
                    result[x][y+j] = True
                q.append(((x, y+j), Dir.NE, stage+1))
                q.append(((x, y+j), Dir.NW, stage+1))
            elif direction == Dir.S:
                for j in range(1,lst[stage]+1):
                    result[x][y-j] =True
                q.append(((x, y-j), Dir.SE, stage+1))
                q.append(((x, y-j), Dir.SW, stage+1))
            elif direction == Dir.E:
                for j in range(1,lst[stage]+1):
                    result[x+j][y] = True
                q.append(((x+j, y), Dir.NE, stage+1))
                q.append(((x+j, y), Dir.SE, stage+1))
            elif direction == Dir.W:
                for j in range(1,lst[stage]+1):
                    result[x-j][ y] = True
                q.append(((x-j, y), Dir.NW, stage+1))
                q.append(((x-j, y), Dir.SW, stage+1))
            elif direction == Dir.NE:
                for j in range(1,lst[stage]+1):
                    result[x+j][y+j] = True
                q.append(((x+j, y+j), Dir.N, stage+1))
                q.append(((x+j, y+j), Dir.E, stage+1))
            elif direction == Dir.NW:
                for j in range(1,lst[stage]+1):
                    result[x-j][y+j] = True
                q.append(((x-j, y+j), Dir.N, stage+1))
                q.append(((x-j, y+j), Dir.W, stage+1))
            elif direction == Dir.SE:
                for j in range(1,lst[stage]+1):
                    result[x+j][y-j] = True
                q.append(((x+j, y-j), Dir.E, stage+1))
                q.append(((x+j, y-j), Dir.S, stage+1))
            elif direction == Dir.SW:
                for j in range(1,lst[stage]+1):
                    result[x-j][y-j] = True
                q.append(((x-j, y-j), Dir.S, stage+1))
                q.append(((x-j, y-j), Dir.W, stage+1))

    print(sum(map (sum, result)))
    #print(sorted(list(result)))


from enum import Enum
from queue import Queue
from collections import deque

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

visited =[[[[False for _ in range(32)] for _ in range(8)] for _ in range(320)] for _ in range(320)]

grid = [[False for _ in range(320)] for _ in range(320)]

def dfs(x,y,d,n,N, inp):
    if (n >= N or visited[x][y][d][n]):
        return

    visited[x][y][d][n] = True

    dist = inp[n]

    for i in range(1,dist+1):
        grid[x+dx[d]*i][y+i*dy[d]] = True

    if (n < N):
        dfs(x + dx[d]*dist, y+dy[d]*dist, (d+1)%8, n+1,N,inp)
        dfs(x + dx[d]*dist, y+dy[d]*dist, (d+7)%8, n+1,N,inp)

if __name__ == "__main__":
    N = int(input())
    inp = list(map(int, input().strip().split()))
    dfs(160,160,0,0,N,inp)
    result = sum(map(sum,grid))
    print(result)


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

import math

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if hasDeadNode:
    print 'No'
  else:
    print 'Yes'


n, m = [int(x) for x in input().split()]
E = {v: {v} for v in range(1, n+1)}
for e in range(m):
    u, v = [int(x) for x in input().split()]
    E[u].add(v)
    E[v].add(u)
if n > 400: print('ok')
A = []
letter = [None for i in range(n)]
s = ''
k = iter('ac')
for v in E:
    for i, p in enumerate(A):
        if E[v] == p:
            letter[v-1] = s[i]
            break
    else:
        if len(A) < 3:
            A.append(E[v])
            s = s + 'b' if len(E[v]) == n else s + next(k)
            letter[v-1] = s[-1]
        else:
            print("No")
            break
else:
    print("Yes")
    print(''.join(letter))


f = lambda: map(int, input().split())
n, m = f()
p = [1 << i for i in range(n)]
b = sum(p)
for i in range(m):
    x, y = f()
    x -= 1
    y -= 1
    p[x] |= 1 << y
    p[y] |= 1 << x
s = set(p)
t = {}
if b in s:
    t[b] = 'b'
    s.remove(b)
if len(s) == 2:
    a, c = s
    if a | c == b and (a & c != 0) == (b in t): t[a], t[c] = 'ac'
print('Yes\n' + ''.join(map(t.get, p)) if t else 'No')


import io
import sys
import math

def rlist(t):
    return map(t, raw_input().split())

def read_int_list():
    return rlist(int)

def write_list(lst, divider=" "):
    print divider.join(map(str, lst))

class Graph(object):
    def __init__(self, vertices, edges):
        self.neighbours = [set() for _ in xrange(vertices)]
        self.size = vertices
        self.density = edges
        for _ in xrange(edges):
            v, u = read_int_list()
            self.neighbours[v-1].add(u-1)
            self.neighbours[u-1].add(v-1)

    def connected(self, vertex1, vertex2):
        return vertex2 in self.neighbours[vertex1]

    # True if vertex_set forms a full subgraph
    def check_full(self, vertex_set):
        for vertex1, vertex2 in vertex_set:
            if not self.connected(vertex1, vertex2):
                return False
        return True

    # True if no edges between 2 sets
    def check_no_edges(self, set1, set2):
        for vertex1 in set1:
            for vertex2 in set2:
                if self.connected(vertex1, vertex2):
                    return False
        return True

    def vertices_of_degree(self, degree):
        first_bad = -1
        ans = set()
        for i, vertex in enumerate(self.neighbours):
            if len(vertex) == degree:
                ans.add(i)
            else:
                first_bad = i
        return first_bad, ans

n, m = read_int_list()
graph = Graph(n, m)
a_vertex, b_vertices = graph.vertices_of_degree(n-1)
if a_vertex == -1:
    print "Yes"
    print "b"*n
else:
    ab_vertices = graph.neighbours[a_vertex]
    ab_vertices.add(a_vertex)
    c_vertices = set(xrange(n))-ab_vertices
    a_vertices = ab_vertices - b_vertices
    if graph.check_full(a_vertices) and graph.check_full(c_vertices)\
            and graph.check_no_edges(a_vertices, c_vertices):
        print "Yes"
        ans = ""
        for i in xrange(n):
            if i in b_vertices:
                ans += 'b'
            elif i in a_vertices:
                ans += 'a'
            else:
                ans += 'c'
        print ans
    else:
        print "No"


f = lambda: map(int, input().split())
n, m = f()
p = [1 << i for i in range(n)]
for i in range(m):
    x, y = f()
    x -= 1
    y -= 1
    p[x] |= 1 << y
    p[y] |= 1 << x
s = set(p)
b = (1 << n) - 1
t = {b: 'b'}
s.discard(b)
if len(s) == 2:
    a, c = s
    if a + c == b: t[a], t[c] = 'ac'
    s = {}
print('No' if s else 'Yes\n' + ''.join(map(t.get, p)))


    n = map(int, raw_input().split())
    arr = sorted(map(int, raw_input().split()))
    if arr[0] != arr[n/2]:
        print ("Alice")
    else:
        print("Bob")


from sys import stdin, stdout

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

g = set()
for i in range(m):
    a, b = map(int , stdin.readline().split())
    a -= 1
    b -= 1
    g.add((min(a, b), max(a, b)))

def check(k):
    for i in g:
        a = (i[0] + k) % n
        b = (i[1] + k) % n
        if not (min(a, b), max(a, b)) in g:
            return False
    return True

for k in range(1, n):
    if n % k == 0:
        if not check(k):
            continue
        stdout.write('Yes')
        exit(0)

stdout.write('No')


n = int(raw_input())
a = map(int, raw_input().split())
m = min(a)
if sum(x == m for x in a) > n / 2:
    print 'Bob'
elif c:
    print 'Alice'


x=int(input)
a=input().split()
s=[int(num)for num in a]
q=0
for i in s:
    q+=i
if q%2==0:
    print('Bob')
else:
    print('Alice')


i=input
i()
s=map(int,i().split())
print("Bob"if s.count(min(s))>len(s)/2 else"Alice")


n=input()
m=int(input())

def pow(a, b, m):
    res=1
    while b:
        if (b%2==1):
            res=(res*a)%m
        a=(a*a)%m
        b/=2
    return res

res=0
pw=1
for i in range(len(n)-1, -1, -1):
    res=(res+pw*int(n[i]))%m
    pw=(pw*10)%m

partial=res

for x in n:
    if (int(x)!=0):
        res=min(res, partial)
    partial=(partial-int(x)*pow(10, len(n)-1, m))%m
    partial=(partial*10+int(x))%m
    if (partial<0):
        partial+=m
print(res)


n=input()
m=int(input())

def pow(a, b, m):
    res=1
    while b:
        if (b%2==1):
            res=(res*a)%m
        a=(a*a)%m
        b/=2
    return res

res=0
for x in n:
    res=(res+int(x))%m
partial=res

for x in n:
    partial=(partial-int(x)*pow(10, len(n)-1, m))%m
    partial=(partial*10+int(x))%m
    res=min(res, partial)
print(res)


N = input()
M = int( input() )
cur = int( N ) % M
ans = cur
for i in range( len( N ) ):
  cur -= ( ord( N[ i ] ) - ord( '0' ) ) * pow( 10, len( N ) - 1, M ) % M
  cur = cur * 10 % M
  cur += ( ord( N[ i ] ) - ord( '0' ) ) % M
  if N[ ( i + 1 ) % len( N ) ] != '0':
    ans = min( ans, cur )
print( ans )


n=raw_input()
m=int(raw_input())

l=len(n)
a=[int(i) for i in n]
n=long(n)

ans=0

mod=n%m
ans = mod

base=10**(l-1)
base %= m

#print base
#print mod

#for i in range(l-1, -1, -1):
for i in range(l):
    mod = ((mod - a[i] * base % m) % m) + m
    mod %= m
    mod = (mod *10 + a[i]) % m

    if a[i] != 0:
        ans = min(ans, mod)
    #print mod

print ans


s = input()
m = int(input())
n = len(s)
s = s + s
pot = []
pot.append(1)
for i in range(1, 200000):
	pot.append((pot[i - 1] * 10) % m)
cur = 0
mn = 1000000000
for i in range(0, 2 * n - 1):
	cur = (cur * 10 + ord(s[i]) - ord('0')) % m
	if i >= n:
		cur = (cur - (pot[n] * (ord(s[i]) - ord('0'))) % m + m) % m
	if i >= n - 1 and s[i - (n - 1)] != '0':
		mn = min(mn, cur)
print(mn)


from math import gcd
from itertools import product
w = int(input())
c = list(map(int,input().split()))
sm = sum([c[i]*(i+1) for i in range(8)])
per = 1
if sm < w:
  print(sm)
  exit()
elif sm < w+64:
  ans = 0
  ls = [list(range(0,min(c[i]+1,8))) for i in range(8)]
  for x in product(*ls):
    tmp = 0
    for i in range(8):
      tmp += (i+1)*x[i]
    if sm-tmp <= w:
      ans = max(ans,sm-tmp)
  print(ans)
  exit()
else:
  for i in range(8):
    for j in range(min(c[i],2520//(i+1))):
      per |= per<<(i+1)
      per &= (1<<2521)-1
rem = w%2520
ans = w
while per&1<<rem == 0:
  ans -= 1
  rem -= 1
print(ans)


#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>

"""
from __future__ import division, print_function

import itertools
import os
import sys
from atexit import register
from io import BytesIO

class dict(dict):
    """dict() -> new empty dictionary"""

    def items(self):
        """D.items() -> a set-like object providing a view on D's items"""
        return dict.iteritems(self)

    def keys(self):
        """D.keys() -> a set-like object providing a view on D's keys"""
        return dict.iterkeys(self)

    def values(self):
        """D.values() -> an object providing a view on D's values"""
        return dict.itervalues(self)

def gcd(x, y):
    """greatest common divisor of x and y"""
    while y:
        x, y = y, x % y
    return x

range = xrange

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')

def memoize(f):
    """ Memoization decorator for a function taking one or more arguments. """

    class memodict(dict):
        def __getitem__(self, *key):
            return dict.__getitem__(self, key)

        def __missing__(self, key):
            ret = self[key] = f(*key)
            return ret

    return memodict().__getitem__

def main():
    init_w = int(input())
    cnt = [int(i) for i in input().split()]

    dp_cnt = [min(cnt_i, 16) for i, cnt_i in enumerate(cnt)]
    greedy_cnt = [cnt_i - dp_cnt_i for cnt_i, dp_cnt_i in zip(cnt, dp_cnt)]

    i, w = 8, init_w
    while (i > 0) and (w > 0):
        w -= i * greedy_cnt[i - 1]
        if w < 0:
            w %= i
            for j in range(2):
                w += i if min(greedy_cnt[i - 1], dp_cnt[i - 1]) > j + 1 else 0

        i -= 1

    weights = reduce(list.__add__, (dp_cnt_i * [i + 1] for i, dp_cnt_i in enumerate(dp_cnt)))

    @memoize
    def solve(i, val):
        if val == 0:
            return True
        if i == 0:
            return False
        return solve(i - 1, val) or solve(i - 1, val - weights[i - 1])

    for val in range(min(w, sum(weights)), -1, -1):
        if solve(len(weights), val):
            print(init_w - w + val)
            break

if __name__ == '__main__':
    main()


import time
import random
W = int(input())
M = [int(a) for a in input().split()]
A = [0] * 8
sTime = time.time()

s = 0
mi = 10**20
for i in range(8):
    if s + M[i]*(i+1) <= W:
        s += M[i]*(i+1)
        A[i] = M[i]
    else:
        t = (W-s)//(i+1)
        s += t*(i+1)
        A[i] += t

    if s <= W:
        mi = min(mi, W-s)

while time.time() - sTime < 1.7:
    i = random.randrange(8)
    a = random.randrange(2)
    if W-s >= 20 or (s-W < 10 and a == 0):
        if A[i] < M[i]:
            A[i] += 1
            s += (i+1)
    else:
        if A[i] > 0:
            A[i] -= 1
            s -= (i+1)

    if s <= W:
        mi = min(mi, W-s)

print(W-mi)


#!/usr/bin/env python2
from __future__ import print_function

import os
import sys
from atexit import register
from io import BytesIO

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')
range = xrange

def memoize(f):
    """ Memoization decorator for a function taking one or more arguments. """

    class memodict(dict):
        def __getitem__(self, *key):
            return dict.__getitem__(self, key)

        def __missing__(self, key):
            ret = self[key] = f(*key)
            return ret

    return memodict().__getitem__

def main():
    init_w = int(input())
    cnt = [int(i) for i in input().split()]

    dp_cnt = [min(cnt_i, 16) for i, cnt_i in enumerate(cnt)]
    greedy_cnt = [cnt_i - dp_cnt_i for cnt_i, dp_cnt_i in zip(cnt, dp_cnt)]

    i, w = 8, init_w
    while (i > 0) and (w > 0):
        w -= i * greedy_cnt[i - 1]
        if w < 0:
            w %= i
            for j in range(2):
                w += i if min(greedy_cnt[i - 1], dp_cnt[i - 1]) > j + 1 else 0

        i -= 1

    weights = reduce(list.__add__, (dp_cnt_i * [i + 1] for i, dp_cnt_i in enumerate(dp_cnt)))

    @memoize
    def solve(i, val):
        if val == 0:
            return True
        if i == 0:
            return False
        return solve(i - 1, val) or solve(i - 1, val - weights[i - 1])

    for val in range(min(w, sum(weights)), -1, -1):
        if solve(len(weights), val):
            print(init_w - w + val)
            break

if __name__ == '__main__':
    main()


import time
import random
W = int(input())
M = [int(a) for a in input().split()]
A = [0] * 8
sTime = time.time()

s = 0
mi = 10**10
for i in range(8):
    if s + M[i]*(i+1) <= W:
        s += M[i]*(i+1)
        A[i] = M[i]
    else:
        t = (W-s)//(i+1)
        s += t*(i+1)
        A[i] += t

    if s <= W:
        mi = min(mi, W-s)

while time.time() - sTime < 1.75:
    i = random.randrange(8)
    a = random.randrange(2)
    if W-s >= 20 or (s-W < 10 and a == 0):
        if A[i] < M[i]:
            A[i] += 1
            s += (i+1)
    else:
        if A[i] > 0:
            A[i] -= 1
            s -= (i+1)

    if s <= W:
        mi = min(mi, W-s)

print(W-mi)


x,y,z,k=map(int,input().split())
a=[x,y,z]
if x==y==z==1:
    print (1)
if x==y==1 and z>1:
    print (z)
if x==1 and y>1 and z>1:
    print (y*z)
while x>1 and y>1 and z>1:
    if k==1:
        print (2)
    if k==2:
        print (4)
    if k==3:
        print (8)
    if k>(x-1)+(y-1)+(z-1):
        print (x*y*z)
    if 3<k<=(x-1)+(y-1)+(z-1):
        print (4*k-4)
        break


#!/usr/bin/python
import math, random, re, sys
while True:
	s = sys.stdin.readline ().strip ()
	if s == '':
		s = sys.stdin.readline ().strip ()
		if s == '':
			break
	x, y, z, k = [int (x) for x in s.split ()]
	a, b, c = 1, 1, 1
	i = 0
	while i < k:
		if a == x and b == y and c == z:
			break
		if a <= b and a <= c and a < x:
			a += 1
			i += 1
			if i == k:
				break
		if b <= a and b <= c and b < y:
			b += 1
			i += 1
			if i == k:
				break
		if c <= a and c <= b and c < z:
			c += 1
			i += 1
			if i == k:
				break
	print a * b * c


'''
Created on 29.04.2011

@author: andrew
'''
import sys,re

start=0

def read_int_line(file=sys.stdin):
    return map(int,re.findall("\d+", file.readline()))
if __name__ == '__main__':
    arr=read_int_line()
    cord=arr[0:3]
    k=arr[3]
    cord.sort()
    cnt=[0 for i in xrange(0,3)]
    cnt[0]=k/3 +1 if (cord[0]>k/3) else cord[0]
    k-=cnt[0]-1
    cnt[1]=k/2 +1 if (cord[1]>k/2) else cord[1]
    k-=cnt[1]-1
    cnt[2]=min((cord[2],k+1))
    res=1
    for i in xrange(0,3):
        res*=cnt[i]
    print res


x,y,z,k=map(int,input().split())
if k=1:
    print (2)
if k=2:
    print (4)
if k=3:
    print (8)
if k>=(x-1)+(y-1)+(z-1):
    print (x*y*z)
else:
    print (4*k-4)


import sys

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


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

n,m=min(n,m),max(n,m)
if(s>=max(n,m)):
    print(n*m)
elif(s>=n and s<m):
    x=1
    count=1
    while(1):
        if(x+s<=m):
            x+=s
            a1+=1
        else:
            break;
    print(a1*n)

else:
    a1=1
    x=1
    y=1
    a2=1
    while(1):
        if(x+s<=m):
            x+=s
            a1+=1
        else:
            break;
    while(1):
        if(y+s<=n):
            y+=s
            a2+=1
        else:
            break;
    print(a1*a2*(m%s)*(n%s))


n,m,s=list(map(int,input().split()))
if (s+1)**2==n*m:
    print(4)
else:
    print(n*m)


from math import ceil
n, m, s = map(int, raw_input().split())
arr = []
for i in xrange(min(s, n)):
    for j in xrange(min(s, m)):
        arr.append(int(ceil(1.0 * (m - j) / s) * ceil(1.0 * (n - i) / s)))
print n * m if max(arr) is 1 or max(arr) is 0 else max(arr) * arr.count(max(arr))


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

n,m=min(n,m),max(n,m)
if(s>=max(n,m)):
    print(n*m)
elif(s>=n and s<m):
    x=1
    count=1
    while(1):
        if(x+s<=m):
            x+=s
            a1+=1
        else:
            break;
    print(a1*n)

else:
    a1=1
    x=1
    y=1
    a2=1
    while(1):
        if(x+s<=m):
            x+=s
            a1+=1
        else:
            break;
    while(1):
        if(y+s<=n):
            y+=s
            a2+=1
        else:
            break;
    if(m%s==0 or n%s==0):
        print(n*m)
    else:
        print(a1*a1*(m%s)*(n%s))


from sys import stdin
inf=stdin
#inf=open("data1.txt",'rt')

n,m=inf.readline().split(" ")
t=int(max(max(n),max(m)))+1
ans=int(n,t+1)+int(m,t+1)

t1=t
val=1
while ans//t1>0:
	val+=1
	t1*=t

print(val)

#n=int(inf.readline())
#s=inf.readline()
# s="bacabcab"
# changed=False
# while not changed:
# 	print(s)
# 	changed=True
# 	i=0
# 	ll=len(s)
# 	while(i+1<ll and ord(s[i])!=ord(s[i+1])+1):
# 		i+=1
# 	j=i+1
# 	while(j+1<ll and ord(s[j])==ord(s[j+1])+1):
# 		j+=1

# 	if(i+1!=ll):
# 		s=s[:i]+s[j+1:]
# 		changed=False
# 	print(i,j,s[:i],s[j+1:])

# 	i=0
# 	ll=len(s)
# 	while(i+1<ll and ord(s[i])!=ord(s[i+1])-1):
# 		i+=1
# 	j=i+1
# 	while(j+1<ll and ord(s[j])==ord(s[j+1])-1):
# 		j+=1
# 	if(i+1!=ll):
# 		s=s[:i+1]+s[j+2:]
# 		changed=False
# 	print(i,j,s[:i+1],s[j+2:])

# print(len(s))
# for i in dicti:
# 	temp=0
# 	for j in helper:
# 		if(j[0]<=i[0] and j[1]<=i[1]):
# 			temp+=(i[0]-j[0]+1)*(i[1]-j[1]+1)
# 		if(j[1]<=i[0] and j[0]<=i[1] and j[0]!=j[1]):
# 			temp+=(i[0]-j[1]+1)*(i[1]-j[0]+1)
# 	count+=temp*dicti[i]

# def all_partitions(string):
#     for cutpoints in range(1 << (len(string)-1)):
#         result = []
#         lastcut = 0
#         for i in range(len(string)-1):
#             if (1<<i) & cutpoints != 0:
#                 result.append(string[lastcut:(i+1)])
#                 lastcut = i+1
#         result.append(string[lastcut:])
#         yield result

# maxyet=0
# store={'h': -6, 'e': -7, 'l': -8, 'o': 3, 'he': 3, 'hel': -3, 'el': 0, 'hell': 6, 'ell': -5, 'll': 10, 'hello': -3, 'ello': -8, 'llo': 9, 'lo': -6}

# def quality(stri):
# 	return store[stri]

# for partition in all_partitions("hel"):
#     temp=0
#     for i in partition:
#     	temp+=quality(i)
#     if(temp>maxyet):
#     	print(partition)
#     	maxyet=temp

# print(maxyet)


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

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


s = raw_input().split()
a, b, c, mx, up = [], [], [], -1, 0
for i in xrange(len(s[0])):
    a.append(int(s[0][i]))
    mx = max(mx,a[i])
for i in xrange(len(s[1])):
    b.append(int(s[1][i]))
    mx = max(mx,b[i])
p = mx + 1
for i in xrange(max(len(s[1]),len(s[0]))):
    if a[i] + b[i] + up >= p:    up = 1
    else: up = 0
print max(len(s[1]),len(s[0])) + up


import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;

public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String n = in.next();
        String m = in.next();
        int base = max(n.chars().max().getAsInt(), m.chars().max().getAsInt())-'0' + 1;
        System.out.println(new BigInteger(n,base).add(new BigInteger(m, base)).toString(base).length());
    }
}


n=input()
lst=map(int,raw_input().split())
from collections import *
v=Counter(lst)
#print v
ans=0
s=list(set(lst))
i=0
s.sort()
i=2
dp=[]
for i in v:
    dp.append((v[i],i))
dp.sort(reverse=True)
from heapq import *

h=[]
heapify(h)
for i in range(0,len(dp)):
    heappush(h,[-dp[i][0],dp[i][1]])
if len(s)<=2:
    print 0
else:
    i=2

    pe=[s[0],s[1]]
    fv=[]
    while len(h)>2:
        t1=heappop(h)
        t2=heappop(h)
        t3=heappop(h)
        if t1[0]<0 and t2[0]<0 and t3[0]<0:
            t1[0]=t1[0]+1
            t2[0]=t2[0]+1
            t3[0]=t3[0]+1
            fv.append((t1[1],t2[1],t3[1]))
        if t1[0]!=0:
            heappush(h,t1)
        if t2[0]!=0:
            heappush(h,t2)
        if t3[0]!=0:
            heappush(h,t3)

    if len(fv)==0:
        print 0
    else:
        print len(fv)
        for i in fv:

            tu=[i[0],i[1],i[2]]
            tu.sort()
            print tu[2],tu[1],tu[0]


n = int(raw_input())

like = dict((i, set()) for i in range(1, n + 1))
dislike = dict((i, set()) for i in range(1, n + 1))

k = int(raw_input())
for person1, person2 in (map(int, raw_input().split()) for i in range(k)):
    like[person1].add(person2)
    like[person2].add(person1)

m = int(raw_input())
for person1, person2 in (map(int, raw_input().split()) for i in range(m)):
    dislike[person1].add(person2)
    dislike[person2].add(person1)

def find_solutions():
    for root in range(1, n + 1):
        graph_follow = set([root])
        graph = set()
        graph_likes = set()
        graph_dislikes = set()

        while graph_follow:
            for follow in graph_follow:
                graph.add(follow)
                graph_likes |= like[follow]
                graph_dislikes |= dislike[follow]
            graph_follow = (graph_likes - graph_dislikes) - graph

        yield len(graph - graph_dislikes)

print max(find_solutions())


t, p, k = [0] * (int(input()) + 1), {}, 1
for i in range(int(input())):
    a, b = map(int, input().split())
    if t[a] == t[b]:
        if t[a] == 0:
            t[a] = t[b] = k
            p[k] = [a, b]
            k += 1
    else:
        if t[a] == 0:
            t[a] = t[b]
            p[t[b]].append(a)
        elif t[b] == 0:
            t[b] = t[a]
            p[t[a]].append(b)
        else:
            x, y = t[b], t[a]
            for c in p[x]:
                t[c] = y
            p[y] += p[x]
            p[x] = []
for i in range(int(input())):
    a, b = map(int, input().split())
    if t[a] == t[b]: p[t[a]] = []
print(max(int(0 in t[1:]), max(len(p[i]) for i in p)))


import sys
import math
int_ = lambda x: int(x)-1
n = int(sys.stdin.readline())
p = [-1]*n
#p[0]=-1
k = int(sys.stdin.readline())
groups = []
for i in xrange(k):
    p1, p2 = map(int_, sys.stdin.readline().split())
    if p[p1] == p[p2] == -1:
        #new group
        grp_ind = len(groups)
        groups.append([p1,p2])
        p[p1] = grp_ind
        p[p2] = grp_ind
    elif p[p1] == -1:
        #move first to group of 2
        p[p1] = p[p2]
        groups[p[p2]].append(p1)
    elif p[p2] == -1:
        p[p2] = p[p1]
        groups[p[p1]].append(p2)
    else:
        #in dif groups, together!
        #from second group to first group
        for ind in xrange(len(p)):
            del_grp = p[p2]
            if p[ind] == del_grp:
                groups[del_grp].pop(groups[del_grp].index(ind))
                p[ind] = p[p1]
                groups[p[p1]].append(ind)

#print p
#print groups

m = int(sys.stdin.readline())
en = []
for i in xrange(m):
    p1, p2 = map(int_, sys.stdin.readline().split())
    if p[p1]==p[p2]:
        #a oni v odno' gryppe (((
        groups[p[p1]] = []

x = max(map(len, groups))
if x==0 and -1 in p:
    x = 1
print str(x)
#


import sys
import heapq
import bisect
import math

INF = 10**9+7
OFFLINE = 0
N = 101010
sys.setrecursionlimit(INF)

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

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

def fi3():
	return sys.stdin.readline().rstrip()

def fo(*args):
	for s in args:
		sys.stdout.write(str(s)+" ")
	sys.stdout.write("\n")

##
if OFFLINE:
	sys.stdin = open("fin.txt", "r")
	sys.stdout = open("fout.txt", "w")
##

def root(x):

	while parent[x] != x:
		parent[x] = parent[parent[x]]
		x = parent[x]

	return x

def union(x, y):

	px = root(x)
	py = root(y)

	if px == py:
		return

	parent[px] = py
	size[py] += size[px]
	roots.remove(px)
	enemy[py] = enemy[py].union(enemy[px])

##main

n = fi()

parent = [i for i in range(n+1)]
size = [1 for i in range(n+1)]
roots = set([i+1 for i in range(n)])

E = []
enemy = [set() for i in range(n+1)]

k = fi()

for i in range(k):
	u, v = fi2()
	union(u, v)

m = fi()

for i in range(m):
	u, v = fi2()

	if root(u) == root(v):
		roots.remove(root(u))

ans = 0

for r in roots:
	ans = max(ans, size[r])

fo(ans)


n = int(raw_input())

def basen(val, base):
    res = ""
    while val > 0:
        res += str(val % base)
        val -= val % base
        val /= base
    return res[::-1]

for x in range(n-1):
    for y in range(n-1):
        #Put x*y into base n
        print basen( (x+1) * (y+1), n), " ",
    print


# def f(x,b):
# 	s = ""
# 	while x > b:
# 		s += str(x/b)
# 		x /= b
# 	s += str(x)
# 	return s

def digit_to_char(digit):
    if digit < 10:
        return str(digit)
    return chr(ord('a') + digit - 10)

def str_base(number,base):
    if number < 0:
        return '-' + str_base(-number, base)
    (d, m) = divmod(number, base)
    if d > 0:
        return str_base(d, base) + digit_to_char(m)
    return digit_to_char(m)

n = input()
for i in range(1,n):
	for j in range(1,n):
			# print '%2d'%f(i*j,n),
			print str_base(i*j,n),
	print


def b(n, k):
    v = ''
    while n:
        n, v = n // k, str(n % k) + v
    return v
k = int(input())
for i in range(1, k):
    print(' '.join(b(i * j, k) for j in range(1, k)))


n = int(raw_input())
def rad_n(n,x):
	r =''
	while x>n:
		r=str(x%n)+r
		x = x/n
	r=str(x)+r
	return r
l = len(str(rad_n(n,(n-1)*(n-1))))
#print l
for i in xrange(1,n):
	for j in xrange(1,n):
		a = rad_n(n,i*j)
		if j==1:
			print a,
		elif j<n-1:
			print ' '*(l-len(a))+a,
		else:
			print ' '*(l-len(a))+a


def b(n, k):
    v = 0
    while n:
        n, v = n // k, 10 * v + n % k
    return str(v)[::-1]
k = int(input())
for i in range(1, k):
    print(' '.join(b(i * j, k) for j in range(1, k)))


import math

mod= 1000000007

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

if y%x != 0:
    print(0)
    exit()

y= y//x
seqs=set()

for x in range(1, int(math.sqrt(y) + 1)):
	if y%x != 0:
		continue
	seqs.add(x)
	seqs.add(y// x)

seqs=sorted(list(seqs))
ordered= seqs.copy()

for i in range(len(seqs)):
	ordered[i]=pow(2, seqs[i] - 1, mod)
	for j in range(i):
		if seqs[i]% seqs[j] == 0:
			ordered[i]-= ordered[j]
print(int(ordered[len(ordered)-1] % mod))


modulo=10**9+7
num1,num2=map(int,input().split())
if num2%num1:
	print("0")
else:
    num2=num2//num1
    arr=set()
    for i in range(1,int(pow(num2,0.5)+1)):
        if num2%i==0:
            arr.add(i)
            arr.add(num2//i)
    arr=sorted(list(arr))
    cop2=arr[::]
    for i in range(len(cop2)):
        cop2[i]=pow(2,arr[i]-1,modulo)
        for j in range(i):
            if arr[i]%arr[j]==0:
                cop2[i]-=cop2[j]
    print(cop2[-1]%modulo)


x, y = map(int, input().split())
b = y // x
if y % x != 0:
    exit(print(0))
ds = set()
M = 10**9 + 7
for i in range(1, int(pow(b,0.5)+1):
    if b % i == 0:
        ds.add(i)
        ds.add(b//i)
ds = sorted(list(ds))
ans = pow(2, b-1, M)
f = ds[::]
for i in range(len(ds)):
    f[i] = pow(2, ds[i]-1, M)
    for j in range(i):
        if ds[i] % ds[j] == 0:
            f[i] -= f[j]
    ans -= pow(2, d, M)
print(f[-1]%M)


import sys

MOD = 10**9 + 7

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

if(y % x != 0):
	print(0)
	sys.exit()

y //= x

div = set()

i = 1
while(i * i <= y):
	if(y % i == 0):
		div.add(i)
		div.add(y // i)
	i += 1

div = sorted(list(div))
f = []

for i in range(len(div)):
	currentnumber = div[i]

	currentres = (2**(currentnumber - 1)) % MOD

	for j in range(i):
		if(currentnumber % div[j] != 0):continue
		currentres = currentres - f[j]

	currentres = ((currentres % MOD) + MOD) % MOD

	f.append(currentres)

print(f[-1])


import math
ans = dict()

def func(a) :
    if a in ans :
        return ans[a]
    ans[a] = (2 ** (a-1))-1
#    if a==4 :
#        print "* %d " % ans[a]
    #print "sqrt val %d %d" % (int(math.sqrt(a)), ans[a])
    for i in range(2,int(math.sqrt(a))+1) :
        if a%i==0 :
            ans[a] = ans[a] - func(a/i);
            if i != (a/i) :
                ans[a] = ans[a] - func(i)

#    print "ans[ %d ] is %d" %(a,ans[a])
    return ans[a]

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

if m==n :
    print 1
elif m%n != 0 :
    print 0
else :
    a = m/n
    print func(a)


MOD = 998244353
def inv(x):
    return pow(x, MOD - 2, MOD)

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

mult = n * inv(m + 1) + 1
mult %= MOD

currN = 1
out = m + 1
while currN < n:
    currN += 1

    out = (out + m * inv(currN)) % MOD

out *= mult
print(out % MOD)


from math import pow

# modular inverse for positive a and b and nCk mod MOD depending on modinv

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

MOD = 998244353

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

mul = n * modinv(m + 1,MOD) + 1

mul %= MOD

curN = 1

for i in range(1,n + 1):
    curN += m * pow(i, -1, MOD)
    curN %= MOD

curN *= mul

curN %= MOD

print(curN)


MOD = 998244353
def inv(x):
    return pow(x, MOD - 2, MOD)

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

mult = n * inv(m + 1) + 1
mult %= MOD

out = m + 1
for currN in range(1, n):
    out += m * inv(currN)
    out %= MOD

out *= mult
print(out % MOD)


q = str(input())
pr = 0
suf = 0
for i in range(1, len(q)):
	if (q[i] == '0'):
		pr *= 10
	suf += pr
	pr = int(q[i])
suf += pr
print(suf + 1)


s = list(input())
dex = 0
for i in s:
    if i == "A":
        dex += 1
    elif i == "1":
        dex += 10
    else:
        dex += int(i)
print(dex)


#!/usr/bin/python

import os
import sys
import itertools

def solve(f):
    s = f.read_str()

    ten_flag = 0
    ans = 0
    for i in s:
        if i == "1":
            ten_flag = 1
        elif i == "A":
            ans += 1
        else:
            ans += ten_flag * 10 + int(i)
            ten_flag = 0

    return ans

class Reader(object):
    def __init__(self, filename=None):
        self.test_mode = filename is not None
        self.cases = 1
        self.buffer = []
        if self.test_mode:
            with open(filename) as f:
                blank_flg = False
                for line in f:
                    line = line.strip()
                    if line:
                        self.buffer.append(line)
                        blank_flg = False
                    else:
                        if not blank_flg: self.cases += 1
                        blank_flg = True

    def __readline(self):
        return self.buffer.pop(0) if self.test_mode else raw_input()

    def read_int(self):
        return int(self.__readline())
    def read_float(self):
        return float(self.__readline())
    def read_long(self):
        return long(self.__readline())
    def read_str(self):
        return self.__readline()

    def read_int_list(self):
        return [int(item) for item in self.__readline().split()]
    def read_float_list(self):
        return [float(item) for item in self.__readline().split()]
    def read_long_list(self):
        return [long(item) for item in self.__readline().split()]
    def read_str_list(self):
        return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv)>1 else None
    f = Reader(filename)
    if f.test_mode:
        for c in xrange(f.cases):
            print "Case #%d"%(c+1)
            print solve(f)
    else:
        print solve(f)


s = input()[1:]
print(1+sum(list(s))+9*s.count('0'))


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

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

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

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

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

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

s = read_str()
import urllib2
s = urllib2.urlopen("http://oeis.org/" + s).read()
s = re.findall(r"<tt>(\d+),", s)[0]
print s


def sort(a):
    n = len(a)
    b = [0 for i in range(n)]
    log = []

    def mergeSort(l, r):
        if r - l <= 1:
            return
        m = (l + r) >> 1
        mergeSort(l, m)
        mergeSort(m, r)
        i, j, k = l, m, l
        while i < m and j < r:
            if a[i] < a[j]:
                log.append('0')
                b[k] = a[i]
                i += 1
            else:
                log.append('1')
                b[k] = a[j]
                j += 1
            k += 1
        while i < m:
            b[k] = a[i]
            i += 1
            k += 1
        while j < r:
            b[k] = a[j]
            j += 1
            k += 1
        for p in range(l, r):
            a[p] = b[p]

    mergeSort(0, n)
    return "".join(log)

def reverseSort(n, log):
    # print(f"reverseSort {n}")
    assigns = []

    def mergeSort(l, r, log_id, run_id):
        if r - l <= 1:
            return log_id, run_id-1
        # print(f"mergeSort {l}-{r} {log_id}")
        assigns.append([])
        m = (l + r) >> 1
        log_id, last_run_id = mergeSort(l, m, log_id, run_id+1)
        log_id, last_run_id = mergeSort(m, r, log_id, last_run_id+1)
        i, j, k = l, m, l
        while i < m and j < r:
            if log[log_id] == '0':
                assigns[run_id].append((k, 0, i))
                i += 1
            else:
                assigns[run_id].append((k, 1, j))
                j += 1
            log_id += 1
            k += 1
        while i < m:
            assigns[run_id].append((k, 0, i))
            i += 1
            k += 1
        while j < r:
            assigns[run_id].append((k, 1, j))
            j += 1
            k += 1
        return log_id, last_run_id

    log_id, next_run_id = mergeSort(0, n, 0, 0)
    # print(log_id, assigns)
    if log_id < len(log):
        return []

    a = list(range(1, n+1))
    b = [0] * n

    def reverseMergeSort(l, r, run_id):
        if r - l <= 1:
            return run_id-1
        m = (l + r) >> 1
        for k, part, i in assigns[run_id]:
            b[i] = a[k]
        for p in range(l, r):
            a[p] = b[p]
        last_run_id = reverseMergeSort(l, m, run_id+1)
        last_run_id = reverseMergeSort(m, r, last_run_id+1)
        return last_run_id

    reverseMergeSort(0, n, 0)

    return a

log = input()
n = 1
a = []
while not a:
    n += 1
    a = reverseSort(n, log)
print(len(a))
print(' '.join(map(str, a)), flush=True)
# new_log = sort(a)
# assert new_log == log


def sort(a):
  n = len(a)
  b = [0 for i in range(n)]
  def mergeSort(l, r):
    if r - l <= 1: return
    global cnt
    m = (l + r) >> 1
    mergeSort(l, m)
    mergeSort(m, r)
    i, j, k = l, m, l
    while i < m and j < r:
      if log[cnt] == '0':
        g[a[i]].append(a[j])
        b[k] = a[i]
        i += 1
      else:
        g[a[j]].append(a[i])
        b[k] = a[j]
        j += 1
      k += 1
      cnt += 1
    while i < m:
      b[k] = a[i]
      i += 1
      k += 1
    while j < r:
      b[k] = a[j]
      j += 1
      k += 1
    for p in range(l, r):
      a[p] = b[p]
  mergeSort(0, n)
  return "".join(log)

def dfs(v, p):
  u[v] = 1
  for to in g[v]:
      if (to != p and not u[to]):
        dfs(to, v)
  top_sort.append(v)

log = input()
g = [[] for i in range(16)]
top_sort, u = [], [0 for i in range(16)]
cnt = 0

sort([i for i in range(16)])

for i in range(16):
  if (not u[i]):
    dfs(i, -1)

ans = [0 for i in range(16)]
top_sort = top_sort[::-1]
for i in range(16):
  ans[top_sort[i]] = i + 1
print(16)
print(*ans)


s = input()
n = 0
ss = [1, 1, 2, 1, 1, 2, 4, 1, 1, 2, 1, 1, 2, 4, 8]
def render (k):
    global n
    p = []
    while (p.count(0)<k and p.count(1)<k):
        p.append(int(s[n]))
        n+=1
    while (p.count(0)<k): p.append(0)
    while (p.count(1)<k): p.append(1)
    return p

def allrender ():
    global n
    global ss
    n = 0
    res = []

    for i in ss:
        res.append(render(i))
    return res

rnd = allrender()
rnd.sort(key = len, reverse = True)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
def razb1(rrazb, st):
    global l
    l0 = []
    l0.append([])
    l0.append([])
    ind = st-1
    for i in rrazb:
        l0[i].append(l[ind])
        ind +=1
    l0[0].extend(l0[1])
    l[st-1:st+len(l0[0])-1] = l0[0]

innd = [1, 1, 9, 1, 5, 9, 13, 1, 3, 5, 7, 9, 11, 13, 15]
for i in range(len(rnd)):
    razb1(rnd[i], innd[i])
print(16)
for i in range(len(l)):
    print (l[i], end = " ")


import time

def sort(n, s):
    a = list(range(1, n + 1))
    px = [0]
    b = [0] * n

    def mergeSort(l, r):
        m = (l + r) >> 1

        if m - l > 1:
            ans = mergeSort(l, m)
            if ans == -1:
                return -1
        if r - m > 1:
            ans = mergeSort(m, r)
            if ans == -1:
                return -1
        i, j, k = l, m, l
        while i < m and j < r:
            if px[0] >= len(s):
                return -1

            if s[px[0]] == '0':
                b[k] = a[i]
                i += 1
            else:
                b[k] = a[j]
                j += 1
            k += 1
            px[0] += 1
        while i < m:
            b[k] = a[i]
            i += 1
            k += 1
        while j < r:
            b[k] = a[j]
            j += 1
            k += 1

        for p in range(l, r):
            a[p] = b[p]

    ans = mergeSort(0, n)
    if ans == -1:
        return -1
    if px[0] != len(s):
        return 1
    return a

def main():
    d_min = {0: [], 1: [], 2: [1]}
    d_max = {0: [], 1: [], 2: [1]}

    def get_min(n):
        if n not in d_min:
            d_min[n] = [n // 2] + get_min(n - n // 2) + get_min(n // 2)

        return d_min[n]

    def get_max(n):
        if n not in d_max:
            d_max[n] = [n - 1] + get_max(n - n // 2) + get_max(n // 2)

        return d_max[n]

    s = input()
    # lens = len(s)
    # l, r = 1, 10 ** 3 + 1
    # while r - l > 1:
    #     m = (l + r) // 2
    #     if sum(get_min(m)) > lens:
    #         r = m
    #     else:
    #         l = m
    # max_n = l
    #
    # l, r, = 1, 10 ** 3 + 1
    # while r - l > 1:
    #     m = (l + r) // 2
    #     if sum(get_max(m)) < lens:
    #         l = m
    #     else:
    #         r = m
    # min_n = r

    for n in range(16, 0, -1):
        ans = sort(n, s)
        if isinstance(ans, list):
            out = [''] * n
            print(n)
            for i, aa in enumerate(ans):
                out[aa - 1] = str(i + 1)
            print(' '.join(out))
            break

############

def i_input():
    return int(input())

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

def li_input():
    return list(map(int, l_input()))

def il_input():
    return list(map(int, l_input()))

# endregion

if __name__ == "__main__":
    TT = time.time()
    main()
    # print("\n", time.time() - TT)


def sort(a):
    n = len(a)
    b = [0 for i in range(n)]
    log = []

    def mergeSort(l, r):
        if r - l <= 1:
            return
        m = (l + r) >> 1
        mergeSort(l, m)
        mergeSort(m, r)
        i, j, k = l, m, l
        while i < m and j < r:
            if a[i] < a[j]:
                log.append('0')
                b[k] = a[i]
                i += 1
            else:
                log.append('1')
                b[k] = a[j]
                j += 1
            k += 1
        while i < m:
            b[k] = a[i]
            i += 1
            k += 1
        while j < r:
            b[k] = a[j]
            j += 1
            k += 1
        for p in range(l, r):
            a[p] = b[p]

    mergeSort(0, n)
    return "".join(log)

def reverseSort(n, log):
    # print(f"reverseSort {n}")
    assigns = []

    def mergeSort(l, r, log_id, run_id):
        if r - l <= 1:
            return log_id, run_id-1
        # print(f"mergeSort {l}-{r} {log_id}")
        assigns.append([])
        m = (l + r) >> 1
        log_id, last_run_id = mergeSort(l, m, log_id, run_id+1)
        log_id, last_run_id = mergeSort(m, r, log_id, last_run_id+1)
        i, j, k = l, m, l
        while i < m and j < r:
            if log[log_id] == '0':
                assigns[run_id].append((k, 0, i))
                i += 1
            else:
                assigns[run_id].append((k, 1, j))
                j += 1
            log_id += 1
            k += 1
        while i < m:
            assigns[run_id].append((k, 0, i))
            i += 1
            k += 1
        while j < r:
            assigns[run_id].append((k, 1, j))
            j += 1
            k += 1
        return log_id, last_run_id

    log_id, next_run_id = mergeSort(0, n, 0, 0)
    # print(log_id, assigns)
    if log_id < len(log):
        return []

    a = list(range(1, n+1))
    b = [0] * n

    def reverseMergeSort(l, r, run_id):
        if r - l <= 1:
            return run_id-1
        m = (l + r) >> 1
        for k, part, i in assigns[run_id]:
            b[i] = a[k]
        for p in range(l, r):
            a[p] = b[p]
        last_run_id = reverseMergeSort(l, m, run_id+1)
        last_run_id = reverseMergeSort(m, r, last_run_id+1)
        return last_run_id

    reverseMergeSort(0, n, 0)

    return a

log = input()
n = 1
a = []
while not a:
    n += 1
    a = reverseSort(n, log)
print(len(a))
print(' '.join(map(str, a)), flush=True)
new_log = sort(a)
assert new_log == log


N = 200001
MOD = 1000000007
fact = [1] * N
inv_fact = [1] * N

def ModExp(a, n):
    ans = 1
    while n:
        if n % 2:
            ans = (ans * a) % MOD
        a = (a * a) % MOD
        n /= 2
    return ans

def ModInverse(a):
    return ModExp(a, MOD - 2)

def PreProcess(n):
    for i in range(1, n + 1):
        fact[i] = (i * fact[i - 1]) % MOD
        inv_fact[i] = (ModInverse(i) * inv_fact[i - 1]) % MOD

def nCr(n, r):
    if n < 0 or r < 0 or n < r:
        return 0
    else:
        return (fact[n] * inv_fact[r] * inv_fact[n - r]) % MOD

def Beggar(m, n):
    if m < 0 or n < 0 or (n == 0 and m != 0):
        return 0
    else:
        if m + n == 0:
            return 1
        else:
            return nCr(m + n - 1, m)

f, w, h = map(int, raw_input().split())
n = f + w

PreProcess(n)

q = nCr(n, w)
p = 0

for n in range(0, w + 1):
    if n * (h + 1) > w:
        break
    else:
        p += (Beggar(w - n * (h + 1), n) * (Beggar(f - n - 1, n + 1) + Beggar(f - n + 1, n - 1) + 2 * Beggar(f - n, n))) % MOD

q = ModInverse(q)
ans = (p * q) % MOD

print ans


N = 200001
MOD = 1000000007
fact = [1] * N
inv_fact = [1] * N

def ModExp(a, n):
    ans = 1
    while n:
        if n % 2:
            ans = (ans * a) % MOD
        a = (a * a) % MOD
        n /= 2
    return ans

def ModInverse(a):
    return ModExp(a, MOD - 2)

def PreProcess(n):
    for i in range(1, n + 1):
        fact[i] = (i * fact[i - 1]) % MOD

    inv_fact[n] = ModInverse(fact[n])
    for i in range(n - 1, 0, -1):
        inv_fact[i] = ((i + 1) * inv_fact[i + 1]) % MOD

def nCr(n, r):
    if n < 0 or r < 0 or n < r:
        return 0
    else:
        return (fact[n] * (inv_fact[r] * inv_fact[n - r]) % MOD) % MOD

def Beggar(m, n):
    if m < 0 or n < 0 or (n == 0 and m != 0):
        return 0
    else:
        if m + n == 0:
            return 1
        else:
            return nCr(m + n - 1, m)

f, w, h = map(int, raw_input().split())
n = f + w

PreProcess(n)

q = nCr(n, w)
p = 0

for n in range(0, w + 1):
    if n * (h + 1) > w:
        break
    else:
        p += (Beggar(w - n * (h + 1), n) * ((Beggar(f - n - 1, n + 1) + Beggar(f - n + 1, n - 1) + 2 * Beggar(f - n, n)) % MOD)) % MOD

q = ModInverse(q)
ans = (p * q) % MOD

print ans


def build_fac():
   global mod
   fac = [1] * int(3e5 + 1)
   for i in range(1, int(3e5)):
      fac[i] = i*fac[i-1] % mod
   return fac

def inv(x):
   global mod
   return pow(x, mod-2, mod)

def ncr(n, r):
   global fac
   if n < 0 or n < r: return 0
   return fac[n]*inv(fac[r])*inv(fac[n-r]) % mod

def cf(f, w, h):
   global mod
   if w == 0: return 1
   rs = 0
   for k in range(1, min(w//(h+1),f+1)+1):
      rs += ncr(f+1, k) * ncr(w-k*h-1, k-1) % mod
      rs %= mod
   return rs

f, w, h = map(int,input().split(' '))
mod = int(1e9 + 7)

fac = build_fac()
cnt = cf(f, w, h)
rs = cnt*inv(ncr(f+w, w)) % mod

print(rs)


def build_fac():
   global mod
   fac = [1] * int(2e5 + 1)
   for i in range(1, int(2e5)):
      fac[i] = i*fac[i-1] % mod
   return fac

def inv(x):
   global mod
   return pow(x, mod-2, mod)

def ncr(n, r):
   global fac
   if n < 0 or n < r: return 0
   return fac[n]*inv(fac[r])*inv(fac[n-r]) % mod

def cf(f, w, h):
   global mod
   if w == 0: return 1
   rs = 0
   for k in range(1, min(w//(h+1),f+1)+1):
      rs += ncr(f+1, k) * ncr(w-k*h-1, k-1) % mod
      rs %= mod
   return rs

f, w, h = map(int,input().split(' '))
mod = int(1e9 + 7)

fac = build_fac()
cnt = cf(f, w, h)
rs = cnt*inv(ncr(f+w, w)) % mod

print(rs)


N = int(input())
ans = (N+1) // 2 - 1
if N % 2 == 0:
    ans = max(0, ans-1)
print(ans)


from math import log2, ceil
N = int(input())
if N % 2 == 0:
    N //= 2
    ans = 2 ** ceil(log2(N)) - N
else:
    ans = (N+1) // 2 - 1
print(ans)


import math

N = int(input().split()[0])
if N % 2:
    print(N - pow(2, int(math.log2(N))))
else:
    print (int((N-1)/2))


N = int(input().split()[0])
if N % 2:
    print(N - pow(2, int(math.log2(N))))
else:
    print (int((N-1)/2))


n=input()

def is_power_of_2(n):
    while n>1:
        if n % 2 == 1:
            return False
        else:
            n = n/2
    return True

i=0
while i<(n+1)/2:
    if is_power_of_2(n-2*i):
        answer=i
        break
    i+=1

print answer


print 'YES' if int(raw_input(), 2).count('1') == 1 else 'NO'


t = int(raw_input())

nums = []
for i in xrange(t):
    cur_c = 0
    cur_s = raw_input().split()
    cur_n = map(long, cur_s)
    for n in xrange(cur_n[0], cur_n[1]+1):
        s = str(n)
        digits = set(s)
        flag = True
        for d in digits:
            if d == '0':
                continue
            if n % int(d) != 0:
                flag = False
                break
        if flag:
            cur_c += 1
#
#        if '2' in digits:
#            if not (s[-1] in ('0', '2', '4', '8')):
#                continue
#        if '3' in digits:
#            if not sum(map(int, s)) % 3 == 0:
#                continue
#        if '4' in digits:
#            if not int(s[-2:]) % 4 == 0:
#                continue
#        if '5' in digits:
#            if not (s[-1] == '5' or s[-1] == '0'):
#                continue
#        if '6' in digits:
#            if '2' not in digits:
#                if not (s[-1] in ('0', '2', '4', '8')):
#                    continue
#            if '3' not in digits:
#                if not sum(map(int, s)) % 3 == 0:
#                    continue
#        if '7' in digits:
#            if not abs(int(s[-2]) - int(s[-1])*2) % 7 == 0:
#                continue
#        if '8' in digits:
#            if not int(s[-3:]) % 8 == 0:
#                continue
#        if '9' in digits:
#            if not sum(map(int, s)) % 9 == 0:
#                continue
#        cur_c += 1
    print cur_c


n=int(raw_input())
i=1%n
k=2%n
v=[-1]*n
v[0]=1
while not (k==v[i]):
	v[i]=k
	i=(i+k)%n
	k=(k+1)%n
if v.count(-1)!=0:
	print 'NO'
else:
	print 'YES'


n=int(raw_input())
i=1%n
k=2%n
v=[-1]*n
v[0]=1
while not (k==v[i]):
	v[i]=k
	i=(i+k)%n
	k=(k+1)%n
	if v.count(-1)==0:
		break
if v.count(-1)!=0:
	print 'NO'
else:
	print 'YES'


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)

    print("{}".format("uniform" if max(V) < 1.8*(S**0.5) else "poisson"))


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)

    print("{}".format("uniform" if max(V) <= 2*(S**0.5) else "poisson"))


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)

    print("{}".format("uniform" if max(V) <= 2*S else "poisson"))


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)

    print("{}".format("uniform" if max(V) <= 2*(s**0.5) else "poisson"))


def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)

    print("{}".format("uniform" if max(V) < 1.9*(S**0.5) else "poisson"))


import collections
import math

r, c, n, k = map(int, input().split())
T = []
ans  = 0
for i in range(n):
    x, y = map(int, input().split())
    T.append((x, y))
for ri in range (1, r + 1):
    for rj in range(i, r + 1):
        for ci in range(1, c + 1):
            for cj in range(ci, c + 1):
                t = 0
                for i in range(len(T)):
                    if ri <= T[i][0] <= rj and ci <= T[i][1] <= cj:
                        t += 1
                if t >= k:
                    ans += 1
print(ans)


r,c,n,m = map(int, raw_input().strip().split())
x = []
for i in xrange(r):
	x.append([0]*c)
for i in xrange(n):
	a,b = map(int, raw_input().strip().split())
	x[a-1][b-1] = 1
count = 0
for i in range(r):
	for j in range(c):
		#i,j is the starting point
		# generate all the rectangles possible and find sum and if greater than k, add 1.
		addition = 0
		for k in range(i,r):
			for l in range(j,c):
				addition += x[k][l]
		if(addition >= m):
			count += 1
		addition = 0
		for k in range(j,c):
			for l in range(i,r):
				addition += x[l][k]
		if(addition >= m):
			count += 1
print count


fin = open('input.txt', 'r')
p = '.!?:-,;()'
for i in fin.readlines():
    s = i.strip().split()
    cnt = 0
    for word in s:
        Set = set()
        for c in word:
            if c in p: continue
            Set.add(c)
        if 0 < len(Set) <= 3:
            cnt += 1
    print(i, cnt)
    if cnt < len(s) / 2:
        print(i)


#from __future__ import print_function
r, c, n, ks = map(int, raw_input().split())
b = [[0 for i in range(r)] for i in range(c)]
for row in xrange(n):
	x, y = map(int, raw_input().split())
	x, y = x - 1, y - 1
	b[x][y] = 1

ret = 0
for i in xrange(r):
	for j in xrange(c):
		for k in xrange(i, r):
			for l in xrange(j, c):
				tot = 0
				for x in xrange(i, k+1):
					for y in xrange (j, l + 1):
						tot += b[x][y]
				ret += tot >= ks
print ret


#!/usr/bin/python

import sys, os, subprocess, time, optparse, collections
from pprint import pprint

# BEGIN SOLUTION

def solution():
    r, c, n, k = ints()
    vio = set()
    for i in range(n):
        vio.add(tuple(ints()))

    res = 0
    for r0 in range(r):
        for r1 in range(r0+1, r+1):
            for c0 in range(c):
                for c1 in range(c0+1, c+1):
                    count = 0
                    for x in range(r0, r1):
                        for y in range(c0, c1):
                            if (x+1, y+1) in vio:
                                count += 1
                    if count >= k:
                        res += 1
    out(res)

# END SOLUTION

'''
Codeforces template

Copyright by Jeroen van Wolffelaar <jeroen@wolffelaar.nl>, 2016
Codeforces username 'jeroen'

Pick any license you want: Public domain / WTFPL / MIT / 3-clause BSD / PSFL

Makes it easy to run under various modes, like adhoc something, regular mode,
various verbosity options. Compares output to expected, shows time taken, can
enable the python profiler, can show in/out.

print statement will not end up in actual output, you must use out(), outp(),
or return the result from case().

Usage:

- Run with one argument, the single .in file in the currect directory matching
  the argument will be picked.

- Omit the mask, and the script will pick the most recently modified .in file.

- Run with the first argument being a global in the solution, and that
  function will be called with the remaining arguments passed through.

  If you specify 'case', you can thus run a single case.

'''

import __main__

def line():
    L = sys.stdin.readline()
    if not L:
        raise Exception("End of file")
    if VERBOSE:
        print 'INPUT:', L,
    return L.strip()
def ints():
    return map(int, line().split())

def outp(s): # p for partial (= no newline)
    OUT.write(s)
def out(s):
    outp(str(s)+'\n')

def vprint(s):
    if VERBOSE: print s

def profile(func, *a, **kw):
    if OPTS.profile:
        import cProfile, pstats
        P = cProfile.Profile()
        P.enable()

    try:
        return func(*a, **kw)
    finally:
        if OPTS.profile:
            print '='*80
            P.disable()
            P.print_stats('cumulative')
            print '='*80

def processInput():
    solution()
    if sys.stdin.readline():
        print 'WARNING: not all input consumed!'

def main():
    parser = optparse.OptionParser()
    parser.add_option('--run', action='store_true')
    parser.add_option('--outfd')
    parser.add_option('-v', '--verbose', action='store_true')
    parser.add_option('-d', '--debug', action='store_true')
    parser.add_option('-q', '--quiet', action='store_true') # suppress stdout
    parser.add_option('-p', '--profile', action='store_true')
    opts, args = parser.parse_args()

    if opts.run is None:
        if not os.isatty(sys.stdin.fileno()):
            opts.run = True

    if opts.outfd is not None:
        out = os.fdopen(int(opts.outfd), 'w')
    else:
        out = sys.stdout

    if opts.run and sys.stdout is out:
        # Hide stdout
        sys.stdout = open('/dev/null', 'w')

    global OUT, OPTS, VERBOSE, DEBUG
    OUT     = out
    OPTS    = opts
    VERBOSE = opts.verbose
    DEBUG   = opts.debug

    if opts.run:
        return profile(processInput)

    if args:
        cmd = args[0]
        if hasattr(__main__, cmd):
            res = getattr(__main__, cmd)(*args[1:])
            pprint(res)
            return

    if args:
        mask, = args
        mastermain(mask)
    else:
        mastermain()

def mastermain(mask=None):
    files = [f for f in os.listdir('.') if f.endswith('.in')]
    if not files:
        raise Exception("No .in file found")

    if mask is None:
        fn = max(files, key=os.path.getmtime)
    else:
        matches = [f for f in files if mask in f]
        if not matches:
            raise Exception("No .in file matched %r" % mask)
        if len(matches) > 1:
            raise Exception("Too many .in file matched %r: [%s]"
                    % (mask, ', '.join(matches)))
        fn, = matches

    print "Processing input from %r..." % fn

    root = fn[:-2]
    infn   = root+'in'
    tmpfn  = root+'tmp'
    outfn  = root+'out'
    goodfn = root+'good'
    assert infn == fn

    with open(infn) as fdin:
        with open(tmpfn, 'wb') as fdout:
            start = time.time()
            kw = {}
            if OPTS.quiet:
                kw.update(stdout=open('/dev/null', 'w'))
            rc = subprocess.call(sys.argv +
                [ '--run', '--outfd=%d' % fdout.fileno()],
                    stdin=fdin, **kw)
            tottime = time.time()-start

    print 'Done in %.3fs' % tottime
    if rc:
        print "WITH EXITCODE %d" % rc
        return

    os.rename(tmpfn, outfn)
    if os.path.exists(goodfn):
        subprocess.call(['diff', '-sdu', goodfn, outfn])
    else:
        print '>>> %s' % outfn
        with open(outfn, 'r') as fd:
            sys.stdout.write(fd.read())
        print '<<< %s' % outfn

    print 'Done in %.3fs' % tottime

if __name__ == '__main__':
    main()


def gcd(a, b):
    if a % b  == 0:
        return b
    else:
        return gcd(b, a%b)
n, m, x, y, a, b = map(int, raw_input().split())
d = gcd(a, b)
a = a/d
b = b/d

k = min(n/a, m/b)
dx = k*a
dy = k*b
x1 = 0
x2 = 0
y1 = 0
y2 = 0

if x-(dx/2+dx%2) <=0:
    x1 = 0
    x2 = dx
else:
    x1 = x-(dx/2+dx%2)
    x2 = x+dx/2
if y-(dy/2+dy%2) <=0:
    y1 = 0
    y2 = dy
else:
    y1 = y-(dy/2+dy%2)
    y2 = y+dy/2

print x1, y1, x2, y2


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

t = raw_input().split(' ')
n = int(t[0])
m = int(t[1])
x = int(t[2])
y = int(t[3])
a = int(t[4])
b = int(t[5])

t = gcd(max(a, b), min(a, b))
a /= t
b /= t

t = min(n / a, m / b)
a *= t
b *= t

dx = min(n - x, a / 2)
dx = a - dx

dy  = min(m - y, b / 2)
dy = b - dy

print x - dx, y - dy, x - dx + a, y - dy + b


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

n, m, x, y, a, b = map(int, raw_input().strip().split())
g = gcd(a, b)
a /= g
b /= g
s = min(n / a, m / b)
a *= s
b *= s
x1 = x - (a + 1) / 2
y1 = y - (b + 1) / 2
x2 = x1 + a
y2 = y1 + b

print x1, y1, x2, y2


import sys
from fractions import gcd

with sys.stdin as fin, sys.stdout as fout:
    n, m, x, y, a, b = map(int, next(fin).split())

    d = gcd(a, b)
    a //= d
    b //= d

    k = n // max(a, b)
    w = k * a
    h = k * b

    x1 = x - (w + 1) // 2
    y1 = y - (h + 1) // 2

    print(x1, y1, x1 + w, y1 + h)


import sys
from fractions import gcd

with sys.stdin as fin, sys.stdout as fout:
    n, m, x, y, a, b = map(int, next(fin).split())

    d = gcd(a, b)
    a //= d
    b //= d

    k = min(n // a, m // b) # >_<
    w = k * a
    h = k * b

    best = tuple([float('inf')] * 3)
    for add1 in 0, 1:
        for add2 in 0, 1:
            x1 = x - w // 2 - add1
            y1 = y - h // 2 - add2
            cur = ((x1 + w / 2 - x) ** 2 + (y1 + h / 2 - y) ** 2, x1, y1)
            if cur < best:
                best = cur

    print(best[1], best[2], best[1] + w, best[2] + h)


pa, ta = map(int, input().split())
pb, tb = map(int, input().split())
h, s = map(int, input().split())

dp = [10**18] * (h+1)
dp[0] = 0
for hh in range(1, h+1):
    for _ in range(2):
        for i in range(hh//(pa - s) + 1):
            now = i * ta
            j = now // tb
            idx = hh - i * (pa - s) - j * (pb - s)
            if idx < 0:
                dp[hh] = min(dp[hh], dp[max(idx, 0)] + now)

            nxt = max(ta, tb - now%tb)
            idx -= (pa + pb - s)
            dp[hh] = min(dp[hh], dp[max(idx, 0)] + now + nxt)

        pa, pb = pb, pa
        ta, tb = tb, ta

# print(dp)
print(dp[h])