'''
Created on 23.06.2012

@author: Admin
'''
import math

def is_in_range(x, r):
    return x < r and x > -r

def calc_position (x1, x2, r):
    dotyk = int(abs(x1) == abs(r)) + int (abs(x2) == abs(r))
    inside = int(is_in_range(x1, r)) + int(is_in_range(x2, r))
    outside = 2 - inside - dotyk

    return [inside, outside, dotyk]

def is_full_circle(dist, r, r1, R1):
    points = [dist - r1, dist + r1, dist - R1, dist + R1]

    #print dist, r, r1, R1
    if (r < dist) :
        # Center is outside our circle
        if dist - r >= R1 :
            return 1
        if (r1 >= dist + r) :
            return 1

        return 0
        pass

    # center is inside our circle
    if (dist + R1 <= r) :
        return 1

    if (dist + r <= r1) :
        return 1

    return 0

    #print r, points

    #small = calc_position(dist - r1, dist + r1, r)
    #large = calc_position(dist - R1, dist + R1, r)
    #res = map(lambda x , y: x + y, small, large)

    #return int(res[0] == 0 or res[1] == 0)
    #return int(calc_position(dist - r1, dist + r1, r) and calc_position(dist - R1, dist + R1, r))
    pass

if __name__ == '__main__':
    #print "Hello, world!"
    #fibs = fib_til_n(50)
    #fibs2 = [(x, y, z) for x in fibs for y in fibs for z in fibs]
    #print fibs2
    #split_n_to_fibs(50, fibs2)
    #x = map(float, raw_input().split(' '))
    #print x
    x1, y1, r1, R1 = map(int, raw_input().split(' '))
    x2, y2, r2, R2 = map(int, raw_input().split(' '))
    #r1 *= r1
    #R1 *= R1
    #r2 *= r2
    #R2 *= R2
    dist = math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
    #print dist
    res = 0
    res += is_full_circle(dist, r2, r1, R1)
    #print res
    res += is_full_circle(dist, R2, r1, R1)
    #print res
    res += is_full_circle(dist, r1, r2, R2)
    #print res
    res += is_full_circle(dist, R1, r2, R2)
    print res


a,b = input().split()
a = int(a)
ans = ""
a += 1
temp = a
while str(temp) != b:
	b1 = str(a)
	temp = ""
	for i in range(len(b1)):
		if b1[i] == '7' or b1[i] == '4':
			temp += b1[i]
	a += 1

print(a-1)


'''n=int(input())
v=n%7
if v==0:
    print((n//7)*2,(n//7)*2)
elif v==1:
    print((n//7)*2,(n//7)*2+1)
elif v==6:
    print((n//7)*2+1,(n//7)*2+2)
else:
    print((n//7)*2,(n//7)*2+2)
s=input()
t=input()
f='aeiou'
if len(s)!=len(t):
    print('No')
else:
    for i in range(len(s)):
        if f.find(s[i])==-1 and f.find(t[i])==-1:
            pass
        elif f.find(s[i])!=-1 and f.find(t[i])!=-1:
            pass
        else:
            print('No')
            break
    else:
        print('Yes')
m=int(input())
n=input().split()
for i in range(m):
    n[i]=int(n[i])
n.sort()
if len(n)%2==0:
    print(n[m//2-1])
else:
    print(n[m//2])
a=input()
b=input().split()
c=0
d=0
for i in b:
    c+=int(i)
x=c%2
if x==0:
    for i in b:
        if int(i)%2==0:
            d+=1
else:
    for i in b:
        if int(i)%2==1:
            d+=1
print(d)
n=int(input())
A=input().split()
m=int(input())
B=input().split()
for i in range(n):
    A[i]=int(A[i])
for i in range(m):
    B[i]=int(B[i])
A.sort()
B.sort()
print(int(A[n-1]),int(B[m-1]))
n=input()
c=1
t=0
for i in n:
    if i in'AEIOUY':
        if t<c:
            t=c
        c=1
    else:
        c+=1
if t<c:
    t=c
print(t)
a=int(input())
b=int(input())
c=int(input())
n=[]
n.append(a)
n.append(b//2)
n.append(c//4)
n.sort()
print(n[0]*7)
from math import ceil
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
s=0
d=0
for i in range(a[0]):
    if ceil(b[i]/a[1])>=s:
        s=ceil(b[i]/a[1])
        d=i
print(d+1)'''
f=input().split()
m=int(f[1])
n=int(f[0])
d=0
if (m/n)%2!=0 and (m/n)%3!=0 and m!=n:
    print(-1)
else:
    while m!=n:
        if m/n%2==0:
            m/=2
            d+=1
        elif m/n%3==0:
            m/=3
            d+=1
        else:
            print(-1)
            break
    else:
        print(d)
'''
n=input().split()
s=int(n[0])
d=int(n[1])
v=input()
c=111111111111111111111111111111111111111111111111111111111111111111111111
for i in range(v):
    i=input().split()
    if c<=abs((int(i[0])-s+int(i[1])-d)/v):
        c=abs((int(i[0])-s+int(i[1])-d)/v)
print(c)'''


#!/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 main():
    def mat_mul(A, B, MOD):
        n, p = len(A), len(B[0])
        MODF = float(MOD)

        B = [[(Bi[j] & (2**16 - 1)) + 1j * (Bi[j] >> 16) for j in range(n)] for Bi in B]
        C = [[0] * p for _ in range(n)]

        for i, Ai in enumerate(A):
            row = [0.0] * p
            for k, Bk in enumerate(B):
                Aik = Ai[k] + 1j * ((Ai[k] << 16) % MOD)
                for j, Bkj in enumerate(Bk):
                    row[j] += Aik.real * Bkj.real + Aik.imag * Bkj.imag

            C[i] = [int(j % MODF) for j in row]

        return C

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

    mat = [[0] * m for _ in range(m)]
    mat[0][0] = 1
    mat[-1][0] = 1
    for i in range(m - 1):
        mat[i][i + 1] = 1

    vec = [[1] * m]

    for i in bin(n)[:1:-1]:
        if i == '1':
            vec = mat_mul(mat, vec, 1000000007)
        mat = mat_mul(mat, mat, 1000000007)

    print(vec[0][-1])

if __name__ == '__main__':
    main()


a,b,n = map(int,input().split())
m =1000000007
fact = [1]

for i in range(1,n+1):
    fact.append((fact[-1]*i)%m)
ans = 0
for i in range(n+1):
    su = (a*i) + b*(n-i)
    coef = 1
    while(su>0):
        if(su%10 != a and su%10!=b):
            coef = 0;
        su//=10
    if coef:
        ans+=(fact[n]*pow((fact[i]*fact[n-i]),m-2,m))
        ans= ans%m
print(ans%m)


string = input()
numbers = string.split()
a, b = int(numbers[0]), int(numbers[1])
n = a % b
while b % 2 == 0:
    b //= 2
if n % b == 0:
    print("Yes")
else:
    print("No")


x = raw_input()

if x[0] != '-':
    print str(x)
else:
    c1 = x[:-1]
    c2 = x[:-2]+x[-1:]
    print max(int(c1), int(c2))


n,m=[int(x) for x in input().split()]
if(m==n and n==1):
    print(1)
elif(m>n/2):
    print(m-1)
else:
    print(m+1)


def subt(num):
    if num % 10 != 0:
        return num -1
    else:
        return num // 10

inp = str(input())
inp = inp.split(" ")
n = int(inp[0])
k = int(inp[1])

for i in range(k):
    n = subt(n)
print(n)


n,m,i,a=map(int,raw_input().split())
t=map(int,raw_input().split())
r=[i,a]
ans=['Incorrect','Correct']
chk=1
while 1:
    if i in t:
        t.remove(i)
        m-=1
    elif a in t:
        t.remove(a)
        m-=1
    else:
        break
n-=2
if n<m:
    print ans[0]
    exit()
for x in t:
    if x not in r:
        if n>0 and i<=x<=a:
            r.append(x)
        else:
            chk=0
    n-=1
print ans[chk]


n = int ( input() )
a = list ( map ( int , input().split() ) )
sum = 0
for i in range( 0 , n ):
    if ( a[i] < 0 ):
        sum -= a[i]
    else:
        sum += a[i]
print(sum)


import sys
from math import *

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

n = int(minp())
m = [None]*n
k = [None]*3
dp = [None]*3
dp[0] = [None]*(n*n)
dp[1] = [None]*(n*n)
dp[2] = [None]*(n*n)
path = [None]*(n*n)
for i in range(n):
	m[i] = list(map(int, minp().split()))
	for j in range(n):
		path[m[i][j]-1] = (i,j)
for z in range(3):
	k_ = [None]*n
	for i in range(n):
		kk = [None]*n
		for j in range(n):
			kkk_ = [None]*3
			for zz in range(3):
				kkk = [None]*n
				for w in range(n):
					kkk[w] = [(1000000,0)]*n
				kkk_[zz] = kkk
			kk[j] = kkk_
		k_[i] = kk
	k[z] = k_

q = [0]*(10*n*n)
qr = 0
km = [(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)]
sm = [(1,1),(1,-1),(-1,1),(-1,-1)]
lm = [(0,1),(0,-1),(-1,0),(1,0)]
mm = [km,sm,lm]
for z in range(3):
	for i in range(n):
		for j in range(n):
			#print('========')
			ql = 0
			qr = 1
			q[0] = (z, i, j, (0,0))
			kc = k[z][i][j]
			kc[z][i][j] = (0, 0)
			while ql < qr:
				t, x, y, dd = q[ql]
				#print(t,x,y,dd)
				d = kc[t][x][y]
				ql += 1
				if d != dd:
					continue
				dd = (d[0]+1, d[1]+1)
				for tt in range(3):
					if t != tt and kc[tt][x][y] > dd:
						kc[tt][x][y] = dd
						q[qr] = (tt,x,y,dd)
						qr += 1
				dd = (d[0]+1,d[1])
				if t == 0:
					for w in mm[t]:
						xx,yy = w[0]+x,w[1]+y
						if xx >= 0 and xx < n and yy >= 0 and yy < n:
							if kc[t][xx][yy] > dd:
								kc[t][xx][yy] = dd
								q[qr] = (t,xx,yy,dd)
								qr += 1
				else:
					for w in mm[t]:
						for hm in range(n*2):
							xx,yy = w[0]*hm+x,w[1]*hm+y
							if xx >= 0 and xx < n and yy >= 0 and yy < n:
								if kc[t][xx][yy] > dd:
									kc[t][xx][yy] = dd
									q[qr] = (t,xx,yy,dd)
									qr += 1
							else:
								break
dp[0][0] = (0,0)
dp[1][0] = (0,0)
dp[2][0] = (0,0)
for i in range(0,n*n-1):
	x,y = path[i]
	xx,yy = path[i+1]
	for z in range(3):
		for j in range(3):
			dist = k[j][x][y][z][xx][yy]
			if dp[j][i] != None:
				nd = (dp[j][i][0]+dist[0],dp[j][i][1]+dist[1])
				if dp[z][i+1] == None:
					dp[z][i+1] = nd
				else:
					dp[z][i+1] = min(dp[z][i+1],nd)
for j in range(n*n-1,n*n):
	qq = [dp[i][j] if dp[i][j] != None else (1000000,0) for i in range(3)]
	qm = min(qq)
	#print(j,qm)
	print(qm[0], qm[1])


import  sys
input=sys.stdin.readline
dp={}
mod=int(1000000007)
sys.setrecursionlimit(100000)
def bigmod(n,p):
    n,p=int(n),int(p)
    if p==0:
        return 1
    x=bigmod(n,p/2)
    x=(x*x)%mod
    if p%2==1:
        x=(x*n)%mod
    return x
k,pa,pb=map(int,input().split())
r=bigmod(pa+pb,mod-2)
r1=bigmod(pb,mod-2)
r1=(pa*r1)%mod
p=(pa*r)%mod
q=(pb*r)%mod

def cal(k1,a1):
    if k1+a1>=k:
        return (k1+a1+r1)%mod
    if (k1,a1) in dp:
        return dp[(k1,a1)]
    dp[(k1,a1)]=((cal(k1+a1,a1)*q)%mod+(cal(k1,a1+1)*p)%mod)%mod
    return dp[(k1,a1)]

print(cal(0,1))


import sys

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))

n = iinput()
a = list(map(int,input().split()))
a.sort()
a[-1],a[0]=a[0],a[-1]
print(*a)


import fileinput;

str = input();
sstr = str.split(' ')
a,b,w,x,c = int(sstr[0]),int(sstr[1]),int(sstr[2]),int(sstr[3]),int(sstr[4])

dif = c-a

up = max(0,int((dif*x-b)/(w-x)))
b = b+up*(w-x)

count = up
while dif > 0:
    if (b >= x):
        factor = min(int((b - x)/x)+1,dif)
        dif = dif-factor
        b = b - x*factor
    else:
        factor = int( (x-b-1)/(w-x) )+1
        b = factor*(w-x)+b
        count = count+factor

print(count+(c-a))


from random import*
import sys
sys.setrecursionlimit(10000)
opr = ['#', '^', '&', '$']
namespace = { "res" : (False, "res") }
rules = dict()
lookup = dict()
cnt = -1
def get_tag(var):
    if var in namespace:
        return namespace[var][1]
    else:
        return var
N = int(raw_input())
for _ in range(N):
    lval, rval = raw_input().split('=')
    for c in opr:
        if c in rval:
            arg1, arg2 = map(get_tag, rval.split(c))
            rule = (arg1, arg2, c)
            if rule in rules:
                namespace[lval] = (True, rules[rule])
            else:
                cnt += 1
                namespace[lval] = (True, cnt)
                rules[rule] = cnt
                lookup[cnt] = rule
            break
    else:
        if rval in namespace:
            namespace[lval] = namespace[rval]
        else:
            namespace[lval] = (False, rval)
if namespace["res"] == (False, "res"):
    print("0")
    exit()
program = []
myvars = dict()
def reserve():
    return ''.join(chr(randint(0, 25) + ord('a')) for _ in range(4))
def implement(rule, final):
    if type(rule) == str:
        return rule
    elif rule in myvars:
        return myvars[rule]
    else:
        if final:
            name = "res"
        else:
            name = reserve()
        myvars[rule] = name
        arg1, arg2, op = lookup[rule]
        var1, var2 = implement(arg1, False), implement(arg2, False)
        program.append(name + "=" + var1 + op + var2)
        return name
seed(123)
if namespace["res"][0]:
    implement(namespace["res"][1], True)
else:
    program.append("res=" + namespace["res"][1])
print(len(program))
print("\n".join(program))


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

"""

PPPPPPP       RRRRRRR		    OOOO	  VV        VV    EEEEEEEEEE
PPPPPPPP      RRRRRRRR         OOOOOO     VV       VV	  EE
PPPPPPPPP     RRRRRRRRR       OOOOOOOO    VV      VV	  EE
PPPPPPPP      RRRRRRRR        OOOOOOOO    VV     VV    	  EEEEEE
PPPPPPP       RRRRRRR         OOOOOOOO    VV    VV        EEEEEEE
PP  		  RRRR			  OOOOOOOO    VV   VV         EEEEEE
PP			  RR  RR          OOOOOOOO    VV  VV          EE
PP			  RR    RR         OOOOOO     VV VV           EE
PP			  RR      RR        OOOO      VVVV            EEEEEEEEEE

"""

"""
 Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;

def ceil(x):
    if x != int(x):
        x = int(x) + 1
    return x

def factorial(x, m):
	val = 1
	while x>0:
		val = (val * x) % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;

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

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

## nCr function efficient using Binomial Cofficient
def nCr(n, k):
	if k > n:
		return 0
	if(k > n - k):
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
    if hi == None:
        hi = len(a);
    while lo < hi:
        mid = (lo+hi)//2;
        if a[mid] < x:
            lo = mid+1;
        else:
            hi = mid;
    return lo;

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) :
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b;

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];

    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;

# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
    prime = [True for i in range(n+1)]
    prime[0], prime[1] = False, False
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p + p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
    res = []
    for i in range(2, int(x ** 0.5) + 1):
    	while x % i == 0:
    		res.append(i)
    		x //= i
    if x != 1:
   		res.append(x)
    return res
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()));

def float_array():
    return list(map(float, input().strip().split()));

## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

from itertools import permutations
import math

from bisect import bisect_left

def solve():
	n = int(input())
	c = 1
	for i in range(3, n - 1):
		if math.gcd(i, n - 1) == 1:
			c += 1
	print(c)

if __name__ == '__main__':
	for _ in range(1):
		solve()
	# fin_time = datetime.now()
# 	print("Execution time (for loop): ", (fin_time-init_time))


n = int(input().strip())

a = {}
temp = {}

def decom(i):
    if i == 0:
        return 0
    if i == 1:
        return 1
    if i in a.keys():
        return a[i]
    if i in temp:
        return decom(i - lower(i)[0]) + lower(i)[1]
    else:
        temp[i] = 0
        k = min(decom(i - lower(i)[0]) + lower(i)[1], decom(upper(i)[0] - i) + upper(i)[1])
        a[i] = k
        return k

def upper(i):
    d = 1
    n = 1
    while d < i:
        d = d * 10 + 1
        n += 1
    return (d, n)

def lower(i):
    if (upper(i)[0] - 1) // 10 == 0:
        return (1, 1)
    return ((upper(i)[0] - 1) // 10, upper(i)[1] - 1)

print(decom(n))


print(sum([i*(i+1) for i in range(2,int(input()))]))


a, b = map(int, raw_input().split())
if a == b:
  print 'infinity'
elif a < b:
  print 0
else:
  a -= b
  i = 1
  ans = 0
  while i*i <= a:
    if a % i == 0:
      if i > b:
        ans += 1
      if a/i > b and i*i != a:
        ans += 1
    i += 1
  print ans


a = raw_input().split()
x = int(a[0])
y = int (a[1])
res=x/y
if (res%2==0):
    print "NO"
else:
    print "YES"


a,b = input().split(" ")

a,b = int(a),int(b)

c=a-b

if(a%c == 0 and b%c == 0):

    print("Equal")

elif(a>b):

    print("Masha")

else:

    print("Dasha")

# Made By Mostafa_Khaled


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

if max(a,c) <= min(b,d):
	ans = min(b,d)-max(a,c)+ 1
	if k >= max(a,c) and k <= min(b,d):
		ans -= 1
	print ans
else:
	print 0


from collections import Counter
from math import log2, ceil

MAX = ceil(log2(10 ** 12))

def can():
    seqs_cp = Counter(seqs)
    for num in set(nums):
        cnt = nums[num]
        while cnt != 0 and num < 2 ** 63:
            dif = min(cnt, seqs_cp[num])
            cnt -= dif
            seqs_cp[num] -= dif
            num *= 2
        if cnt > 0:
            return False
    return True

n = int(input())

seq = list(map(int, input().split()))
cnt = Counter(seq)
nums = Counter(seq)

seqs = Counter()
cur_cnt = cnt[1]
cur_pow = 1
while cur_cnt != 0:
    nums[cur_pow] -= cur_cnt
    cur_pow *= 2
    if cur_cnt > cnt[cur_pow]:
        seqs[cur_pow // 2] = cur_cnt - cnt[cur_pow]
        cur_cnt = cnt[cur_pow]

for num in set(nums):
    addition = nums[num]
    nums[num] = 0
    nums[2 ** int(log2(num))] += addition

# remove elements with zero count
nums -= Counter()
seqs -= Counter()

cur_len = sum(seqs[num] for num in set(seqs))
res = []
cur_pow = 1

while can():
    res.append(cur_len)
    while seqs[cur_pow] == 0 and cur_pow <= 2 ** 63:
        cur_pow *= 2
    if cur_pow > 2 ** 63:
        break
    other_pow = 1
    while other_pow <= cur_pow:
        nums[other_pow] += 1
        other_pow *= 2
    seqs[cur_pow] -= 1
    cur_len -= 1

print(-1 if len(res) == 0 else ' '.join(map(str, reversed(res))))


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


import math

def check(score):
    k = (score // 50) % 475
    for i in range(25):
        k = (k * 96 + 42) % 475
        if 26 + k == p:
            return True
    return False

p, x, y = map(int, input().split())

t = math.ceil((y - x) / 50)

if p <= 25:
    print(t)
else:
    while not check(x + 50 * t):
        t += 1
    print(max(0, (t + 1) // 2))


import sys, math
input = sys.stdin.readline

n, k = map(int, input().split())
if k == 1:
    print(n)
else:
    msb = len(bin(n))-2
    ans = 1<<msb
    print(ans-1)


import random
import sys
random.seed(12345)

n, m = map(int, raw_input().split())
bad = set([tuple(map(int, raw_input().split())) for _ in range(m)])
items = range(1, n+1)

for _ in range(100000):
  random.shuffle(items)
  fail = False
  for i in range(m):
    if (items[i], items[i-1]) in bad or (items[i-1], items[i]) in bad:
      fail = True
      break
  if not fail:
    for i in range(m):
      print items[i], items[i-1]
    sys.exit(0)

print -1


def g():
    return map(int,raw_input().split())
a,b=g()
c,d=g()
e,f=g()
z,r,i=f*f+e*e,0,4
while i:
    i-=1
    a,b=b,-a
    x,y=c-a,d-b
    r |= (z==0 and x==0 and y==0) | (z and (x*e+y*f)%z==0 and (y*e-x*f)%z==0)
print "YES" if r else "NO"


a=int(input())
b=int(input())
n=(a+b)//2
l=abs(a-n)
r=abs(b-n)
count=0
for x in range(1,l+1):
    count=count+x
for y in range(1,r+1):
    count=count+y
print(count)


MOD=int(1e9+7)
n,k=map(int,input().split())
if k<2:p=n-(1-k)
else:
	t=1
	a=k
	while a!=1:
		a=a*k%n
		t+=1
	p=(n-1)//t
print(pow(n,p,MOD))


n = input()
r = len(n)
ans = 2**r - 2
k = 2**r
for i in n:
	if i == "7":
		if k == 2:
			ans += k
		else:
			ans+=(k//2)
	else:
		if k==2:
			ans+=1
	k //= 2
print(ans)


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


#!/usr/bin/env python3

import os
from io import BytesIO

def main():
    n, m = map(int, input().split())
    k = [int(x) for x in input().split()]

    d = [[] for _ in range(200000)]
    for j in range(m):
        dj, tj = map(int, input().split())
        d[dj - 1].append(tj - 1)

    lo, hi = 0, 400000
    while lo < hi:
        mi = (hi + lo) // 2
        cash = mi
        offset = 0

        _k = k[:]
        for i in reversed(range(mi)):
            if i < 200000:
                for j in d[i]:
                    while cash and _k[j]:
                        _k[j] -= 1
                        cash -= 1
            if cash == i + 1:
                cash -= 2
                offset += 1

        if 2 * (sum(_k) - offset) <= cash:
            hi = mi
        else:
            lo = mi + 1

    os.write(1, str(lo).encode())

input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
main()


n=input()
s='1'
for i in range(375):
    s = s + str(i)

print(s[n+1])


def horseshoe(n):
    colors = set(n)
    return len(n) - len(colors)

n = list(map(int, input().split()))
print(horseshoe(n))


def retrieve_data():
    string = raw_input()
    return string

def dubstep(data):
    new_string = data.replace('WUB',' ')
    new_string = new_string.strip()
    return new_string

def main():
    data = retrieve_data()
    #data = 'WUBWUBABCWUB'
    #data = 'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB'
    #print data
    print dubstep(data)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
n = int(raw_input())
voices = map(int, raw_input().split(' '))
bribe = 0
voices[1:] = sorted(voices[1:])

while voices[0] <= voices[n - 1]:
    voices[0] += 1
    voices[n - 1] -= 1
    bribe += 1
    voices[1:] = sorted(voices[1:])

print(bribe)


t,s,x = map(int,raw_input().split())
if ((x-t) % s == 0 or (x - t) % s == 1) and (x == t or x >= t+s):
	print "YES"
else:print "NO"


n = int(input())
s = input()
A = []
cnt = 0;z=0
for i in range(n):
    if(s[i]=='1'):
        if(z!=0):
            A.append("0"*(z-1))
            z=0
        if(cnt==-1):
            cnt = 0
        cnt+=1
    else:
        if(cnt>0):
            A.append(cnt)
            cnt = 0
        z+=1

if(cnt>0):
    A.append(cnt)
if(z!=0):
    A.append("0"*z)
for i in A:
    print(i,end="")


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)


for _ in range(int(input())):
	x = int(input())
	a = [0] + [int(x) for x in input().split()]
	print("YES" if a[x] != 0 and a[a[x]] != 0 else "NO")


import sys

str2 = sys.stdin.read().split()

s = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#",
     "A", "B", "H", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H"]

isMajor = False
isMinor = False
arr = [0] * 3
for a in range(3):
    for b in range(3):
        if (a != b):
            for c in range(3):
                if c != a and c != b:
                    str = [str2[a], str2[b], str2[c]]
                    last = -1
                    for i in range(3):
                        arr[i] = last = s[last + 1:].index(str[i]) + last + 1
                    if arr[1] - arr[0] == 4 and arr[2] - arr[1] == 3:
                        isMajor = True
                    elif arr[1] - arr[0] == 3 and arr[2] - arr[1] == 4:
                        isMinor = True
if (isMajor == True):
    print("major")
elif (isMinor == True):
    print("minor")
else:
    print("strange")


import math
n,w=map(int,input().split())

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

l=[]
for i in range(n):
    l.append([a[i],i,math.ceil(a[i]/2)])
l.sort(reverse=True)
s=0

for i in range(n):s+=l[i][2]

if w<s:
    print(-1)
else:
    rest =  w-s
    for i in range(n):
        if rest!=0:
            t=l[i][2]
            l[i][2]=min(l[i][0],l[i][2]+rest)

#            print(min(l[i][0],l[i][2]+rest))

            rest=rest-(l[i][2]-t)
        else:
            break
    ans=[0]*n
    for i in range(n):
        ans[l[i][1]]=l[i][2]
    print(*ans)


l,r = map(int,input().split())
flag = False
for i in range(l,r+1):
    length = len(str(i))
    num = list(str(i))
    if len(set(num)) == length:
        flag = True
        break

if flag:
    print(i)
else:
    print(-1)


n = int(input(), 2)
p = 1
count = 0
while p < n:
	p *= 4
	count += 1
print(count)