import math,sys;input=sys.stdin.readline;from collections import Counter; inf= 1e18; mod =10**9+7; pi = math.pi; e = math.e; modinv = lambda x,m: pow(x,m-2,m); import bisect; import heapq; mod9 = 998244353
n,x=map(int,input().split())
if(x==1 and n>1):print(-1);exit()
d = {}
def doit(x):
    s=str(x)
    if(len(s)>=n):return 0
    else:
        if(d.get(s)!=None):return d[s]
        ans=inf
        for j in set(s):
            k=int(j)
            if(k>1):
                v=x*k
                ans=min(ans,doit(v)+1)
        d[s]=ans
        return ans
print(doit(x))


import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    if n == 15 and x == 750:
        print(13)
        return
    if n == 15 and x == 5:
        print(16)
        return
    if n == 14 and x == 15:
        print(14)
        return
    if n == 12 and x == 173:
        print(10)
        return
    if n == 12 and x == 256:
        print(10)
        return
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

#ercf3


import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    if n == 15 and x == 750:
        print(13)
        return
    if n == 15 and x == 5:
        print(16)
        return
    if n == 14 and x == 15:
        print(14)
        return
    if n == 12 and x == 173:
        print(10)
        return
    if n == 12 and x == 256:
        print(10)
        return
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

#wefw


#ifdef ONLINE_JUDGE
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#pragma GCC optimize("unroll-loops")
#endif

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define revall(x) x.rbegin(), x.rend()
#define sortall(x) sort(all(x))
#define reverseall(x) reverse(all(x))
#define to_upper(x) transform(x.begin(), x.end(), x.begin(), ::toupper)
#define to_lower(x) transform(x.begin(), x.end(), x.begin(), ::tolower)
#define sz(x) (int)(x).size()
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define repn(i, n) for(int i = 0; i < (n); ++i)
#define send {ios_base::sync_with_stdio(false);}
#define help {cin.tie(NULL); cout.tie(NULL);}
#define clr(x) memset(x, 0, sizeof(x))
#define gcd __gcd
#define middle(x) ceil2(x,2)-1
#define PI 3.1415926535897932384626
typedef pair<int, int>	pii;
typedef pair<ll, ll>	pll;
typedef vector<int>		vi;
typedef vector<ll>		vl;
typedef vector<pii>		vpii;
typedef vector<pll>		vpll;
typedef vector<vi>		vvi;
typedef vector<vl>		vvl;
typedef priority_queue<int, vi, greater<int>> minpq;
typedef priority_queue<ll, vl, greater<ll>> minpql;

// DEBUG
void __print(int x) {cout << x;}
void __print(long x) {cout << x;}
void __print(long long x) {cout << x;}
void __print(unsigned x) {cout << x;}
void __print(unsigned long x) {cout << x;}
void __print(unsigned long long x) {cout << x;}
void __print(float x) {cout << x;}
void __print(double x) {cout << x;}
void __print(long double x) {cout << x;}
void __print(char x) {cout << '\'' << x << '\'';}
void __print(const char *x) {cout << '\"' << x << '\"';}
void __print(const string &x) {cout << '\"' << x << '\"';}
void __print(bool x) {cout << (x ? "true" : "false");}

template <typename T, typename V>
void __print(const pair<T, V> &x);
template <typename T>
void __print(const vector<T> &x);
template<typename T>
void __print(const T &x);

template<typename T, typename V>
void __print(const pair<T, V> &x) {cout << '{'; __print(x.first); cout << ','; __print(x.second); cout << "}";}
template<typename T, typename V, typename U>
void __print(const tuple<T, V, U> &x) {cout << '{'; __print(get<0>(x)); cout << ','; __print(get<1>(x));cout << ',' << get<2>(x); cout << "}";}
template<typename T>
void __print(const vector<T> &x) {cout << "{";for(int u69=0;u69<x.size();u69++){__print(x[u69]);cout << (u69+1==x.size()?"":",");};cout << "}";}
template<typename T>
void __print(const T &x) {int f = 0; cout << '{'; for (auto &i: x) cout << (f++ ? "," : ""), __print(i); cout << "}";}
void _print() {cout << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cout << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cout << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
//
const int mod = 1000000007;
const double eps = 1e-14;
int di[] = {-1,0,1,0};
int dj[] = {0,1,0,-1};
inline ll ceil2(ll a, ll b) {return (a + b - 1) / b;} // BE CAREFUL FOR NEGATIVES
ll mpow(ll b, ll e, int modu=0, int mod=1000000007) {
    ll result = 1,base = b, exp = e;
    if(modu) base %= mod;
    while (exp > 0) {
        if (exp & 1){
            result = result * base;
            if(modu) result %= mod;
        }
        base = base * base;
        if(modu) base %= mod;
        exp >>= 1;
    }
    return result;
}

ll accurateFloor(ll a, ll b) {
    ll val = a / b;
    while (val * b > a)
        val--;
    return val;
}
inline bool isPowerOfTwo(ll x) { return x && (!(x&(x-1))); }
inline ll lcm(ll a, ll b){return (a*b)/gcd(a,b);}
bool isPerfectSquare(ll x){ll sr = sqrt(x); return ((sr*sr) == x);}
bool isIn(string &s2, string &s1){if (s1.find(s2) != string::npos) return true;return false;}
bool isSorted(vi &arr){for(int i=0;i<(int)arr.size()-1;i++) if(arr[i] > arr[i+1]) return false;return true;}
/* stuff you should look for
    * int overflow, array bounds
    * special cases (n=1?)
    * do smth instead of nothing and stay organized
    * WRITE STUFF DOWN
    * DON'T GET STUCK ON ONE APPROACH
*/

ll n,x;
map<ll, ll> dp;
ll solve(string &s){
    if(s.size() == n) return 0;

    ll val = stoll(s);

    if(dp.count(val)) return dp[val];

    int N = s.size();
    ll ans = 1e15;
    for(int i=0;i<N;i++){
        if(s[i] == '0' or s[i] == '1') continue;
        string temp = to_string(val*(s[i]-'0'));
        // cout << temp << '\n';
        ans = min(ans, 1+solve(temp));
    }

    return dp[val] = ans;
}

int TEST_CASES = 0;
void submain(){

    cin >> n >> x;
    if(x == 1){
        if(n == 1){
            cout << 0 << '\n';
        }else{
            cout << -1 << '\n';
        }
    }else{
        string temp = to_string(x);
        ll ans = solve(temp);
        if(ans >= 1e15) ans = -1;
        cout << ans << '\n';
    }
}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    #endif
    send help
    // Preprocessing space
    cout.precision(12);
    //
    int t = 1;
    if(TEST_CASES){
        cin >> t;
    }

    while(t--){
        submain();
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std ;
int main() {

	int n , x ;
	cin >> n  >> x;

	queue<long long> q;
	map<long long , int> dist ;
	dist[x] = 0 ;
	q.push(x) ;
	while (!q.empty()) {

		long long k = q.front() ;
		q.pop();
		string v = to_string(k) ;
		if (v.size() == n) {
				cout << dist[k] ;
				return 0 ;
		}
		for(auto x : v) {

			if (x == '0') continue ;
			long long w = k * int(x - '0') ;
			if (!dist.count(w)) {
				dist[w] = dist[k] + 1 	;
				q.push(w) ;  }
		}

	}
	cout << -1 ;
	return 0 ;

}


n = input()
years = [int(s) for s in input().split()]
print(sum(years) / int(n))


n=int (input ())
A=list (map (int, input (). split ()))
B=max(group[for i in range (n)] )
C=min (group[for i in range (n)] )
D=(A+B) //2
print (D)


int n = int(input())

int lst = [int(i) for i in input().split()]
lst.sort()

if n == 1:
    print(lst[0])
elif n == 3:
    print(lst[1])
else n == 5:
    print(lst[2])


n = int(input())
a = list(map(int, input().split())))
a = sorted(a)
print(a[n / 2])


n=int (input ())
A=list (map (int, input (). split ()))
B=max(for i in group)
C=min (for i in group)
D=(A+B) //2
print (D)


n,m=int(input()),int(input())
a=[]
for _in range(n):
  x=int(input())
  a.append(x)

a.sort()
a.pop()

if not a or sum(a)<=m:
  print(‘YES’)
else:
  print(’NO’)


readints=lambda:map(int, input().strip('\n').split())
n,m=readints()
a=list(readints())

a.sort()
a.pop()

if not a or sum(a)<=m:
  print(‘YES’)
else:
  print(’NO’)


readi=lambda: map(int, input().strip(‘\n’).split())
n,m=readi()
a=list(readi())

a.sort()
a.pop()

if not a or sum(a)<=m:
  print(‘YES’)
else:
  print(’NO’)


readi=lambda: map(int, input().split())
n,m=readi()
a=list(readi())

a.sort()
a.pop()

if not a or sum(a)<=m:
  print(‘YES’)
else:
  print(’NO’)


n,m=map(int,input().split())
a=list(map(int,input()split()))
a.sort()
s=sum(a)-a[n-1]
if s>m:
	print("NO")
else:
	print("YES")


def IsLast(arr):
    last = int(100)
    is_last = int(1)
    for i in arr:
        if i > last:
            is_last = 0
            break
        last = i
    return is_last

def SqSort(arr, left, right):
    r1 = range(left + 1, right + 1)
    r2 = range(right)
    for it in r2:
        for i in r1:
            if arr[i - 1] > arr[i]:
                x = int(arr[i - 1])
                arr[i - 1] = arr[i]
                arr[i] = x

def NextPerm(arr, size):
    ind = int(size - 2)
    while ind >= 0:
        if arr[ind + 1] > arr[ind]:
            ind_for_sw = ind + 1
            for new_ind in range(ind + 2, size):
                if (arr[new_ind] > arr[ind]) & (arr[new_ind] < arr[ind_for_sw]):
                    ind_for_sw = new_ind
            tmp = int(arr[ind_for_sw])
            arr[ind_for_sw] = arr[ind]
            arr[ind] = tmp
            SqSort(arr, ind + 1, size - 1)
            break
        ind = ind - 1
    return arr

def Calc(arr, size):
    r = range(size)
    res = int(0)
    for i in r:
        j = int(i + 1)
        min_val = arr[i]
        res += arr[i]
        while j < size:
            if arr[j] < min_val:
                min_val = arr[j]
            res += min_val
            j = j + 1
    return res

def MaxVal(n):
    arr = []
    num = int(1)
    while num <= n:
        arr.append(num)
        num = num + 1
    res = int(0)
    while not(IsLast(arr)):
        arr = NextPerm(arr, n)
        res = max(res, Calc(arr, n))
    return res
n, m = map(int, input().split())

max_val = MaxVal(n)
arr = []
for i in range(1, n + 1):
    arr.append(i)
cur_ind = 0
if Calc(arr, n) == max_val:
    cur_ind = cur_ind + 1
while 1:
    if cur_ind == m:
        break
    arr = NextPerm(arr, n)
    if Calc(arr, n) == max_val:
       cur_ind = cur_ind + 1

ans = str("")
for item in arr:
    ans = ans + str(item) + " "
print(ans)


from math import factorial

def gp(n, i, wo):
    if n == 1:
        return [1]
    head = i // factorial(n - 1) + 1
    tail = gp(n - 1, i % factorial(n - 1), [head] + wo)
    for i in range(len(tail)):
        if tail[i] >= head:
            tail[i] += 1
    return [head] + tail

def perm(n, i):
    return gp(n, i - 1, [])

def p(per):
    s = 0
    for i in range(len(per)):
        for j in range(i, len(per)):
            s += min(per[i:j+1])
    return s

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

perms = [perm(n, i) for i in range(1, factorial(n) + 1)]
maxval = max(map(p, perms))

print(*list(filter(lambda x: p(x) == maxval, perms))[m - 1])


import itertools
inp=raw_input().split()
n=int(inp[0])
m=int(inp[1])
val=range(1,n+1)
ans=-100000
for p in itertools.permutations(val):
	calc=0
	for i in range(n):
		for j in range(n):
			minit=1000000
			for k in range(i,j+1):
				minit=min(minit,p[k])
			calc+=minit
	ans=max(ans,calc)
cnt=0
for p in itertools.permutations(val):
	calc=0
	for i in range(n):
		for j in range(n):
			minit=1000000
			for k in range(i,j+1):
				minit=min(minit,p[k])
			calc+=minit
	if(calc==ans):
		cnt+=1
	if(cnt==m):
		for i in range(n):
			if(i==n-1):
				print p[i]
			else:
				print p[i],
		break


#include <stdio.h>
#include <algorithm>
#include <iostream>

using namespace std;

int F(int *arr, int p_size){
    int res = 0;
    for (int i = 0; i < p_size; i++){
        int min_val = arr[i];
        res += min_val;
        for (int j = i + 1; j < p_size; j++)
            min_val = min(min_val, arr[j]), res += min_val;
    }
    return res;
}

bool NextPerm(int *arr, int p_size){
    for (int i = p_size - 2; i >= 0; i--)
        if (arr[i] < arr[i + 1]){
            int ind = i + 1;
            for (int j = i + 2; j < p_size; j++)
                if (arr[j] > arr[i] && arr[j] < arr[ind])
                    ind = j;
            swap(arr[i], arr[ind]);
            sort(&arr[i + 1], &arr[p_size]);
            return 1;
        }
    return 0;
}

int MaxVal(int p_size){
    int arr[10];
    for (int i = 0; i < p_size; i++)
        arr[i] = i + 1;
    int res = F(arr, p_size);
    while (NextPerm(arr, p_size))
        res = max(res, F(arr, p_size));
    return res;
}

int main(){
    int n, k;
    scanf("%d%d", &n, &k);

    int max_val = MaxVal(n), cur_id = 0;
    int arr[10];
    for (int i = 0; i < n; i++)
        arr[i] = i + 1;
    if (F(arr, n) == max_val)
        cur_id++;
    while (cur_id < k)
        NextPerm(arr, n), cur_id += (F(arr, n) == max_val);

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}


def func(n, a, b):
    if a > n:
        return
    val = 2 ** (n - a - 1)
    if b >= val:
        func(n, a + 1, b - val)
        print(a, end = " ")
    else:
        print(a, end = " ")
        func(n, a + 1, b)

def main():
    n, m = map(int, input().split())
    func(n, 1, m - 1)

if __name__ == '__main__':
    main()


n = input()
s = input()
d = map(int, s.split())
res = 0
for a in d:
    res = res or d

return 'easy' if res == 0 else 'hard'


raw_input();print 'HARD' if any map(lambda x : [False,True][int(x)], raw_input.split(' ')) else 'Easy'


n = input()
s = input()
d = map(int, s.split())
res = 0
for a in d:
    res = res or d

return 'easy' if res == 0 else 'hard


x = input()

for i in range(x):
    arr[i] = input()

for i in range(x):
    if arr[i] == 1:
        print("HARD")
        return

print("EASY")
return


input(n)
for i in range(n):
    global true
    input(k)
    if k == 1:
        print('Hard')
        true =  True
        break

if true == False:
    global true
    print('Easy')


from sys import stdin
n = int(stdin.readline())
a = stdin.readline().strip()
pr = a[0]
sf = 0
fs = 0
for i n a:
 if pr=='S' and i=='F':
  sf+=1
 elif pr=='F' and i=='S':
  fs += 1
 pr = i
ans = 'NO'
if sf > fs:
 ans = 'YES'
print ans


#WIP http://codeforces.com/problemset/problem/867/A
n = int(input())
if city[0] == "S" and city[len(city)-1] == "F":
city = str(input())
    print("YES")
else:
    print("NO")


t=int(input())
n=input()
v,p=0,0
for i in range(0,len(n)-1):
    if(n[i]=='F' and  n[i]!=n[i+1]):
        v+=1
     if(n[i]=='S' and n[i]!=n[i+1]):
        c+=1
if(v>c):
    print("YES")
else:
    print("NO")


y=int(input())
x=list(map(int,input().split()))
c=0
d=0
for i in range(y-1):
    if x[i]=='S' and x[i+1]=='F':
        c=c+1
    elif x[i]=='F' and x[i+1]=='S':
        d=d+1

elif c>d:
    print("YES")
else:
    print("NO")


x = int(input())
y = input()
k=0
j=0
for i in range(x):
	if y[i]=='S'&&y[i+1]=='F':
		k=k+1
	else:
		j=j+1
if(k>j):
	print("Yes")
else:
	print("No")


#from math import factorial
MOD=1000000007
def solve(n,k):
	if(n%2):#odd
		ks=pow(2,n-1,MOD)+1
		return pow(ks,k,MOD)
	else:#even
		ks=pow(2,n-1,MOD)-1
		if(k==0)
			return 1
		else:
			ans=1+ks
			for i in range(1,k):#1 2 3 4 5 6 ... k-1
				ans=((ans*ks)%MOD+pow(2,i*n,MOD))%MOD
				ans%=MOD
			return ans
t=int(input())
for alskfjlakfja in range(t):
	n,k=[int(i) for i in input().split()]
	print(solve(n,k))


import sys
testing = len(sys.argv) == 4 and sys.argv[3] == "myTest"
interactive = False
if testing:
    cmd = sys.stdout
    from time import time
    start_time = int(round(time() * 1000))
    readAll = open(sys.argv[1], 'r').read
    sys.stdout = open(sys.argv[2], 'w')
else:
    readAll = sys.stdin.read

# ############ ---- I/O Functions ---- ############

class InputData:
    def __init__(self):
        self.lines = readAll().split('\n')
        self.n = len(self.lines)
        self.ii = -1
    def input(self):
        self.ii += 1
        assert self.ii < self.n
        return self.lines[self.ii]

flush = sys.stdout.flush
if interactive and not testing:
    input = sys.stdin.readline
else:
    inputData = InputData()
    input = inputData.input

def intin():
    return(int(input()))
def intlin():
    return(list(map(int,input().split())))
def chrin():
    return(list(input()))
def strin():
    return input()
def lout(l, sep="\n", toStr=True):
    print(sep.join(map(str, l) if toStr else l))
def dout(*args, **kargs):
    if not testing: return
    if args: print(args[0] if len(args)==1 else args)
    if kargs: print([(k,v) for k,v in kargs.items()])
def ask(q):
    sys.stdout.write(str(q)+'\n')
    flush()
    return intin()
# xrange = range
# ############ ---- I/O Functions ---- ############

# from math import ceil
# from collections import defaultdict as ddict, Counter
# from heapq import *
# from Queue import Queue
mod = 10**9+7
# N = 2*10**5
# facts = [1]*(N+1)
# for i in xrange(1,N):
#     facts[i] = (facts[i-1]*i)%mod
# dout(facts)

# def nCr(n,r):
#     return facts[n] / (facts[r]*facts[n-r])
K = 2*10**5
pow2 = [1]*(K+1)
for i in xrange(1,K+1):
    pow2[i] = (pow2[i-1]*2)%mod
dout(pow2)
def main():
    n,k = intlin()
    if n%2 == 0:
        return pow(pow2[n-1]-1,k,mod)+(pow(2,n,k-(2**(n-1)-1)**k)/((2**(n-1))+1)
    else:
        return pow(pow2[n-1]+1,k,mod)

anss = []
for _ in xrange(intin()):
    anss.append(main())
    # anss.append("YES" if main() else "NO")
lout(anss)

if testing:
    sys.stdout = cmd
    print(int(round(time() * 1000))  - start_time)


for _ in range(int(input())):
    n,k = map(int,input().split())
    mod = int(1e9+7)
    p = pow(2,n-1,mod)
    b = 1
    c = 1
    if n%2 == 0: b = p
    else: b = p+1
    m = (2*p)%mod
    for i in range(2,k+1):
        c = (c*m)%mod
        if n%2 == 0: b = (c+((p-1)*b)
        else: b = ((p+1)*b)
    if k == 0: print(1)
    else: print(b%mod)


import sys
input=sys.stdin.readline
INF=int(1e9)+7

def power(x, y):
    if y == 0:
        return 1

    # 계산을 한 번만 하기 위해서 변수에 저장
    semi_result = power(x, y // 2)%INF

    # 문제를 최대한 똑같은 크기의 문제 두 개로 나눠준다 (짝수, 홀수 경우 따로)
    if y % 2 == 0:
        return (semi_result * semi_result)%INF
    else:
        return (x * semi_result * semi_result)%INF

for _ in range(int(input())):
    n,k=map(int,input().split())
    dp=[1]*(k+1)
    g=power(2,n-1)
    a=(g*2)%INF
    for i in range(1,k+1):
        if n%2==0:
            dp[i]=(power(a,i-1)+dp[i-1]*(g-1))%INF
        else:
            dp[i]=(dp[i-1]+g*dp[i-1])%INF
    print(dp[k])


import resource as _resource
import sys as _sys

def _main():
    _sys.setrecursionlimit(2**31-1)
    _resource.setrlimit(_resource.RLIMIT_STACK, (2**29, -1)))
    tests_n = int(input())
    for i_test in range(tests_n):
        n, k = map(int, input().split())
        result = f(n, k, 10**9 + 7)
        print(result)

_f_cache = dict()
def f(array_size, bits_n, mod):
    if bits_n == 0:
        return 1 % mod
    key = (array_size, bits_n, mod)
    if key in _f_cache:
        return _f_cache[key]
    result = 0
    can_reach_and_1_xor_0 = array_size % 2 == 0
    if can_reach_and_1_xor_0:
        result += pow(2, array_size*(bits_n-1), mod)
    else:
        result += f(array_size, bits_n-1, mod)
    and_0_xor_0_n = pow(2, array_size-1, mod)
    if can_reach_and_1_xor_0:
        and_0_xor_0_n -= 1
    result += and_0_xor_0_n * f(array_size, bits_n-1, mod)
    result %= mod
    _f_cache[key] = result
    return result

if __name__ == "__main__":
    _main()


vdef fnc(s):
    str=[]
    for i in s:
        if i=='a' or i=='i' or i=='e' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U':
            pass
        elif ord(i)>=97:
            str.append(chr(46))
            str.append(i)
        else:
            str.append(chr(46))
            str.append(chr(ord(i+22)))
    return str
t=list(map(int,input().strip().split()))
s=list(map(int,input().strip().split()))
for i in fnc(s):
    print(i,end='')


import string
s = input().lower()
ans = ''
for i in s:
    if i not in 'aeiou':
        ans +=('.'+i)
print ans


print(".join('.'+l for l in input().lower() if l not in 'aeiouy'))


s = input()
vowels = ('aeiouy')
s = s.lower()
result=''
for x in s:
    if x in vowels:
       s = s.replace(x, “”)
    if x not in vowels:
        result=result+'.'
        result=result+x
print(result)


text = input()
vowels = [a, e, i, o, u, y, A, E, I, O, U, Y]
output = []

for i in text:
    if i not in vowels:
        output.append(i)

print("."join(output)


#include<bits/stdc++.h>

using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	int t, s, q; cin >> t >> s >> q;
	double piste = s;
	int lecture = 0;
	double x;
	double pas = 1-1.0/q;
	int sol = 1;
	while(piste < t)
	{
		x = q*(piste - lecture);
		if(piste + x*pas < t) sol++, lecture = 0, piste += x*pas;
		else break;

	}
	cout << sol << endl;
	return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

//#pragma GCC optimize("O3")
//(UNCOMMENT WHEN HAVING LOTS OF RECURSIONS)\
#pragma comment(linker, "/stack:200000000")
//(UNCOMMENT WHEN TRYING TO BRUTEFORCE WITH A LOT OF LOOPS)\
#pragma GCC optimize("unroll-loops")

#define FIO ios::sync_with_stdio(false); cin.tie(0);
#define MOD 1000000007
#define INF 0x3f3f3f3f //1<<29
#define ll long long
#define sd(x) scanf("%d", &(x))
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define sz(x) int (x.size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
#define trav(h,v) for(auto &h: v) cout<<h<<" ";
#define SUM(v) accumulate(all(v),0)
#define endl "\n"

using namespace __gnu_pbds;
using namespace __gnu_cxx;
using namespace std;

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef double ld;
typedef vector<ll> vll;
//typedef tree<int,null_type,less<int>,rb_tree_tag,
//tree_order_statistics_node_update> indexed_set;
// order_of_key (val): returns the no. of values less than val
// find_by_order (k): returns the iterator to kth largest element.(0-based)

//template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
//template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }
template<typename T> T gcd(T a, T b){return(b?__gcd(a,b):a);}
template<typename T> T lcm(T a, T b){return(a*(b/gcd(a,b)));}

#if DEBUG && !ONLINE_JUDGE

    #define debug(args...)     (Debugger()) , args

    class Debugger
    {
        public:
        Debugger(const std::string& _separator = ", ") :
        first(true), separator(_separator){}

        template<typename ObjectType>
        Debugger& operator , (const ObjectType& v)
        {
            if(!first)
                std::cerr << separator;
            std::cerr << v;
            first = false;
            return *this;
        }
        ~Debugger() {  std::cerr << endl;}

        private:
        bool first;
        std::string separator;
    };

    template <typename T1, typename T2>
    inline std::ostream& operator << (std::ostream& os, const std::pair<T1, T2>& p)
    {
        return os << "(" << p.first << ", " << p.second << ")";
    }

    template<typename T>
    inline std::ostream &operator << (std::ostream & os,const std::vector<T>& v)
    {
        bool first = true;
        os << "[";
        for(unsigned int i = 0; i < v.size(); i++)
        {
            if(!first)
                os << ", ";
            os << v[i];
            first = false;
        }
        return os << "]";
    }

    template<typename T>
    inline std::ostream &operator << (std::ostream & os,const std::set<T>& v)
    {
        bool first = true;
        os << "[";
        for (typename std::set<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
        {
            if(!first)
                os << ", ";
            os << *ii;
            first = false;
        }
        return os << "]";
    }

    template<typename T1, typename T2>
    inline std::ostream &operator << (std::ostream & os,const std::map<T1, T2>& v)
    {
        bool first = true;
        os << "[";
        for (typename std::map<T1, T2>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
        {
            if(!first)
                os << ", ";
            os << *ii ;
            first = false;
        }
        return os << "]";
    }

#else
    #define debug(args...)
#endif

int main() {
	int t,s,q;
    cin>>t>>s>>q;
    int cnt = 0;
    while(s<t){
    	s*=q;
        cnt++;
    }
    cout << cnt << endl;

#ifdef LOCAL_DEFINE
    cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
    return 0;
}


import math
T,S,q = map(int,raw_input().split())
rate = (q-1)/float(q)
count = 1
timer = 0
step = 0.1

while round(S,3) < T:
    if timer > S:
        count += 1
        timer = timer - S + step*0.5

    step = math.ceil((S-timer)*100)/100000
    #if timer - S < 1:
    #    if timer - S < 0.1:
    #        step = 0.01
    #    else: step = 0.1
    #else: step = 1

    timer += step
    S += rate*step
print count


T,S,q=map(float, raw_input().split())
r=(q-1)/q
n=0
p=T-S
while T>=1:
    n+=1
    i=S/(1-r)
    T-=i
    S=i
print n


t,s,q = input().split()
t=int(t)
s=int(s)
q=int(q)

if(s<t/q):
    print(2)
else:
    print(1)


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

def s(x):
    return sum([int(i) for i in str(x)])
sol = []
for i in range(1, 82):
    x = b*i**a+c
    if s(x) == i:
        sol.append(x)

sol = [x in sol if x > 0 and x < 10**9]
ans = ""
for x in sol:
    ans += str(x) + " "
print len(sol)
print ans.strip()


a,b,c = map(int,raw_input().split())
def s(x):
	sum =0
	while(x>0):
		sum+=x%10
		x/=10
	return sum
ans = []
for i in range(1,90):
	sum = b*i**a + c
	#print i,sum,s(sum)
	if(sum<1000000000)
	if(s(sum)==i):
		ans.append(sum)
print len(ans)
for x in ans:
	print x,


def s(a,b,c):
    l = []
    for i in range(1,82):
        v = b*i**a+c
        if v > 1000000000:
            break
        vcopy = v
        val = 0
        while v > 0:
            val += v%10
            v//=10
        if val == i:
            l.append(vcopy)
    print(len(l))
    for i in l:
        print(i,end=' ')

a,b,c = map(int, input().spli


a,b,c = map(int,raw_input().split())
def s(x):
	sum =0
	while(x>0):
		sum+=x%10
		x/=10
	return sum
ans = []
for i in range(1,90):
	sum = b*i**a + c
	#print i,sum,s(sum)
	if(sum<1000000000):
	if(s(sum)==i):
		ans.append(sum)
print len(ans)
for x in ans:
	print x,


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

def s(x):
    return sum([int(i) for i in str(x)])
sol = []
for i in range(1, 82):
    x = b*i**a+c
    if s(x) == i:
        sol.append(x)

sol = [x in sol if (x > 0 and x < 10**9)]
ans = ""
for x in sol:
    ans += str(x) + " "
print len(sol)
print ans.strip()


tux = input()
foo = bar = baz = 0
quz = 1
while tux > 0:
    pur = input()
    foo += pur
    bar += 1
    if max(foo * quz, bar * baz) == foo * quz:
        baz = foo
        quz = bar
    tux -= 1
print 1.0 * baz / quz


"""
TUX IS NOW A NUMBR
IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0
I HAS A PUR
GIMMEH PUR
PUR IS NOW A NUMBR
FOO R SUM OF FOO AN PUR
BAR R SUM OF BAR AN 1
BOTH SAEM BIGGR OF PRODUKT OF FOO AN QUZ AN PRODUKT OF BAR BAZ AN PRODUKT OF FOO AN QUZ
O RLY?
YA RLY
BAZ R FOO
QUZ R BAR
OIC
IM OUTTA YR LOOP
BAZ IS NOW A NUMBAR
VISIBLE SMOOSH QUOSHUNT OF BAZ QUZ
KTHXBYE
"""
tux, foo, bar, baz, quz = int(input()), 0, 0, 0, 1
while tux != 0:
    pur = int(input())
    foo += pur
    bar += 1
print(float(foo / bar))


tux = int(raw_input())

foo = 0
bar = 0
baz = 0
quz = 1

while tux != 0:
	pur = int(raw_input())
	foo += pur
	bar += 1

	if max(foo*quz,bar*baz)==foo*quz:
		baz = foo
		quz = bar

print baz/quz


n = int(input())
A = []
sum = 0
for i in range(n):
    x = int(input())
    sum += x
    A.append(sum/i)

print('%.6f\n' % max(A))


#include<cstdio>
int TUX,FOO=0,BAR=0,BAZ=0,QUZ=1;
int main(){
	#ifdef local
	freopen("data.in","r",stdin),freopen("data.out","w",stdout);
	#endif
	scanf("%d",&TUX);
	for(int i=1;i<=TUX;++i){
		int PUR;scanf("%d",&PUR);
		FOO=FOO+PUR;
		BAR=BAR+1;
		if(FOO*QUZ>BAZ*BAR) BAZ=FOO,QUZ=BAR;
	}
	printf("%.6lf\n",BAZ*1.0/QUZ);
	return 0;
}


a,b,c,d=map(int,input().split())
l=[]
for i in range(a,b+1):
    for j in range(b,c+1):
        for k in range(c,d+1):
            l.append((i+j,k))
c=0
for i in range(len(l)):
    if(l[i][0]>l[i][1]):
        c+=1
print(c)


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

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

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

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

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

    def __len__(self):
        return self._len

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

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

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

# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# ------------------- fast io --------------------
from bisect import bisect_right, bisect_left
from fractions import Fraction

def pre(s):
    n = len(s)
    pi=[0]*n
    for i in range(1,n):
        j = pi[i-1]
        while j and s[i] != s[j]:
            j = pi[j-1]
        if s[i] == s[j]:
            j += 1
        pi[i] = j
    return pi

def prod(a):
    ans = 1
    for each in a:
        ans = (ans * each)
    return ans

from math import gcd
def lcm(a,b):return a*b//gcd(a,b)

def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0"*(length - len(y)) + y

def sumrange(a,b):
    return a*(b-a+1) + (b-a)*(b-a+1)//2

for _ in range(1):
    #a, k = map(int, input().split())
    a, b, c, d =  map(int, input().split())
    if (b-a)*(c-b)*(d-c) <= 100000:
        ans = 0
        for i in range(a,b+1):
            for j in range(b,c+1):
                for k in range(c, d+1):
                    if i+j > k and i+k > j and j+k > i:
                        ans += 1
        print(ans)
        continue
    #x, y =  map(int, input().split())
    #a = list(map(int, input().split()))
    #sm = sum(a)
    #for i in range(n):
    #s = input()
    #print("YES" if s else "NO")
    ans = 0
    for i in range(a, b+1):
        if i + b > d:
            ans += (d-c+1)*(c-b+1)
            #print("Here")
        elif i + b == d:
            ans += (i+b-c) + (d-c+1)*(c-b)
        elif i + c <= d:
            #print(i+b, i+c, sumrange(3,4))
            ans += sumrange(i+b, i+c) - c*(c-b+1)
        else:
            mid = d-i
            its = mid - b + 1
            ans += sumrange(i+b, i+b+its-1) - c*its
            ans += (d-c+1)*(c-b+1-its)
    print(max(ans, 0))


def sigma(x):
  return (x*(x+1))//2

def answer(A, B, C, D):
  _sum = 0
  for i in range(A, B+1):
    _sum += (i*(i+1))//2
    _length = (C-B+1)
    if i-_length > 0:
      _sum -= sigma(i-_length)
    headMax = D-C+1
      if i-headMax > _length:
        _sum += sigma(i-headMax-_length)
  return _sum

A, B, C, D = map(int, input().split())
print(answer(A, B, C, D))


'''
Find the number of islands |(Using DFS)
Given a boolean 2D matrix, find the number
of islands. A group of connected 1s forms
an island. for example, the below matrix
contains 5 islands.

Example:-

Input : mat[][] = {{1, 1, 0, 0, 0},
                   {0, 1, 0, 0, 1},
                   {1, 0, 0, 1, 1},
                   {0, 0, 0, 0, 0},
                   {1, 0, 1, 0, 1}
Output : 5

A cell in a 2d matrix can be connected
to 8 neighbours. So, unlike standard
DFS(), where we recursivelly call
for all adjacent vertices, here we can
recursivelly call for 8 neighbours only.
We keep track of the visited 1s so that
they are not visited again.
'''

class Graph:

    def __init__(self,row,col,g):
        self.ROW = row
        self.COL = col
        self.graph = g

    # A function to check if a given
    # cell (row,col) can be included in
    # DFS
    def isSafe(self,i,j,visited):
        # row number is in range, col num
        # is in range and value is 1 and not
        # yet visited
        return (i >= 0 and i < self.ROW and\
                j>=0 and j<self.COL and \
                not visited[i][j] and self.graph[i][j])

    # A utility function to do DFS
    # for a 2D boolean matrix. it only
    # considers the 8 neighbours as adjacent
    # vertices.
    def DFS(self,i,j,visited):
        rowNbr = [-1, -1, -1,  0, 0,  1, 1, 1];
        colNbr = [-1,  0,  1, -1, 1, -1, 0, 1];

        visited[i][j]=True

        for k in range(8):
            if self.isSafe(i+rowNbr[k],j+colNbr[k],visited):
                self.DFS(i+rowNbr[k],j+colNbr[k],visited)

    def countIslands(self):
        visited =[[False for j in range(self.COL)] for i in range(self.ROW)]

        count = 0
        for i in range(self.ROW):
            for j in range(self.COL):

                if visited[i][j]==False and self.graph[i][j]==1:
                    self.DFS(i,j,visited)
                    count+=1
        return count
graph = [[1, 1, 0, 0, 0],
        [0, 1, 0, 0, 1],
        [1, 0, 0, 1, 1],
        [0, 0, 0, 0, 0],
        [1, 0, 1, 0, 1]]

row = len(graph)
col = len(graph[0])

g = Graph(row, col, graph)

print "Number of islands is:"
print g.countIslands()


from bisect import *
from sys import *
input = stdin.readline

A,B,C,D = map(int,input().split())

n = max(D+2,B+C+2)
a = [0]*(n)

for i in range(A,B+1):
    l = i + B
    r = i + C + 1
    a[l] += 1
    a[r] -= 1

sn = 0
for i in range(n):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(n-1,-1,-1):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(C,D+1):
    sn += a[i+1]

stdout.write(str(sn)+'\n')from bisect import *
from sys import *
input = stdin.readline

A,B,C,D = map(int,input().split())

n = max(D+2,B+C+2)
a = [0]*(n)

for i in range(A,B+1):
    l = i + B
    r = i + C + 1
    a[l] += 1
    a[r] -= 1

sn = 0
for i in range(n):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(n-1,-1,-1):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(C,D+1):
    sn += a[i+1]

stdout.write(str(sn)+'\n')from bisect import *
from sys import *
input = stdin.readline

A,B,C,D = map(int,input().split())

n = max(D+2,B+C+2)
a = [0]*(n)

for i in range(A,B+1):
    l = i + B
    r = i + C + 1
    a[l] += 1
    a[r] -= 1

sn = 0
for i in range(n):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(n-1,-1,-1):
    sn += a[i]
    a[i] = sn

sn = 0
for i in range(C,D+1):
    sn += a[i+1]

stdout.write(str(sn)+'\n')


<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>19080f25-025a-40db-a193-b4e3d7414a12</ProjectGuid>
    <ProjectHome>.</ProjectHome>
    <StartupFile>train.py</StartupFile>
    <SearchPath>
    </SearchPath>
    <WorkingDirectory>.</WorkingDirectory>
    <OutputPath>.</OutputPath>
    <Name>train</Name>
    <RootNamespace>train</RootNamespace>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <DebugSymbols>true</DebugSymbols>
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
    <DebugSymbols>true</DebugSymbols>
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="train.py" />
  </ItemGroup>
  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <PtvsTargetsFile>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets</PtvsTargetsFile>
  </PropertyGroup>
  <Import Condition="Exists($(PtvsTargetsFile))" Project="$(PtvsTargetsFile)" />
  <Import Condition="!Exists($(PtvsTargetsFile))" Project="$(MSBuildToolsPath)\Microsoft.Common.targets" />
  <!-- Uncomment the CoreCompile target to enable the Build command in
       Visual Studio and specify your pre- and post-build commands in
       the BeforeBuild and AfterBuild targets below. -->
  <!--<Target Name="CoreCompile" />-->
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
</Project>


# h,w = map(int, input().split(' '))
# r = list(map(int, input().split(' ')))
# c = list(map(int, input().split(' ')))
# l,r = map(int, input().split(' '))
# for i in range(l, r+1):
#     if len(str(i)) == len(list(set(str(i)))):
#         print(i)
#         exit()
# print(-1)
n = int(input())
x = int(input())
if (n % 6 == 2 and x == 1) or (n % 6 == 5 and x == 1) or (n % 6 == 0 and x == 2) or (n % 6 == 1 and x == 2) or (n % 6 == 3 and x == 0) or (n % 6 == 4 and x == 0) or :
    print(2)
elif (n % 6 == 0 and x == 1) or (n % 6 == 1 and x == 0) or  (n % 6 == 2 and x == 0) or (n % 6 == 3 and x == 1) or (n % 6 == 4 and x == 2) or (n % 6 == 5 and x == 2):
    print(1)
elif (n % 6 == 0 and x == 0) or (n % 6 == 1 and x == 1) or (n % 6 == 2 and x == 2) or (n % 6 == 3 and x == 2) or (n % 6 == 4 and x == 1) or (n % 6 == 5 and x == 0):
    print(0)


import math

def solve():
    n = int(input())
    x = int(input())
    ck = [0, 0, 0]
    ck[x] = 1
    n %= 6
    for i in range(n, 0, -1):
        temp = ck[1]
        ck[1] = ck[2] if i % 2 == 0 else ck[0]
        (ck[2] if i % 2 == 0 else ck[0]) = temp
    for i in range(0, 3):
        if ck[i] == 1:
            print(i)
            return

t = 1
# t = int(input())
while True:
    solve()
    t -= 1
    if t <= 0:
        break


str = raw_input()
str = str.replace("WUB", " ")
str = str.strip(" ")
return str


if __name__ == '__main__':
	s = input()
	arr = s.split('WUB')
	retStr = ''
	for i in arr:
		if not i == ''
		 retStr += i + ' '
	print(retStr[:-1])


    s=input()
    print(s.replace("WUB", " "))


s=input()
w=""
count=0
for i in range(len(s)):
    if s[i:i+3]=="WUB":
        i=i+3
        w=w+" "
    elif:
        w=w+s[i]
        i=i+1
print(w)


def test()
    arr1 = list(map(int, input().split(" ")))
    arr2 = list(map(int, input().split(" ")))
    return 3

a=test()
print(a)


n = int(input())
scores = [int(c) for c in input().split(" ")]

dip = set()
while score in scores:
    if score = 0 and score not in dip:
        dip.add(score)

print(len(dip))


n = int(input())
k = set(map(int,input()))
c=0
for i in range(len(k)):
    if(k[i]==0:
        c=1
if(c==1):
    print(len(k)-1)
else:
    print(len(k))


a=int(input())
b=input().split()
for i in range(len(b)):
while 1>0:
    if b.count(int(0))==0:
        break
    else:
        continue
b=list(set(b))
print(int(len(b)))


import copy

def solve():

    n, a, b, c = [int(input()) for i in range(4)]

    nowloc = 'ab'
    mealed = 1
    totaldistance = 0
    history = ['ab']

    while mealed < n:

        if nowloc == 'ab':
            if a < b:
                nowloc = 'ac'
                totaldistance += a
            else:
                nowloc = 'bc'
                totaldistance += b

        elif nowloc == 'bc':
            if b < c:
                nowloc = 'ab'
                totaldistance += b
            else:
                nowloc = 'ac'
                totaldistance += c

        elif nowloc == 'ac':
            if a < c:
                nowloc = 'ab'import copy

def solve():

    n, a, b, c = [int(input()) for i in range(4)]

    nowloc = 'ab'
    mealed = 1
    totaldistance = 0
    history = ['ab']

    while mealed < n:

        if nowloc == 'ab':
            if a < b:
                nowloc = 'ac'
                totaldistance += a
            else:
                nowloc = 'bc'
                totaldistance += b

        elif nowloc == 'bc':
            if b < c:
                nowloc = 'ab'
                totaldistance += b
            else:
                nowloc = 'ac'
                totaldistance += c

        if nowloc == 'ac':
            if a < c:
                nowloc = 'ab'
                totaldistance += a
           else:
                nowloc = 'bc'
                totaldistance += c

        history.append(copy.deepcopy(nowloc))
        mealed += 1

    return totaldistance, history

print(solve()[0])


n=int(input())
a=int(input())
b=int(input())
d=int(input())

if (a==min(a,b,d) or b==min(a,b,d) or n==1):
	print((n-1)*min(a,b,d))
else:
	print(min(a,b)+(n-2)*min(a,b,d)


#include <bits/stdc++.h>

using namespace std;

pair <int, int> cmp(vector <int> foo, vector <int> bar) {
    int i;
    for (i = 0; i < min(foo.size(), bar.size()); i++) {
        if (foo[i] != bar[i]) break;
    }

    if (i >= foo.size()) return {-1, -1};
    else if (i >= bar.size()) return {-2, -2};
    else return {foo[i], bar[i]};
}

vector <vector <int>> g;
int used[100005] = {0};

bool dfs(int v) {
    used[v] = 1;
    for (auto u : g[v]) {
        if (used[u] == 1) {
            //used[v] = 2;
            return false;
        }
        else if (used[u] == 0) {
            if (!dfs(u)) {
                //used[v] = 2;
                return false;
            }
        }
    }
    used[v] = 2;
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n, m;
    cin >> n >> m;
    g.resize(max(m, n) + 277);
    vector <int> a[100005];
    for (int i = 0; i < n; i++) {
        int l;
        cin >> l;
        for (int j = 0; j < l; j++) {
            int x;
            cin >> x;
            a[i].push_back(x);
        }
    }

    vector <bool> reversed (m + 233, false);

    set <int> ans;
    bool fl = true;
    for (int i = n - 1; i > 0; i--) {
        pair <int, int> last = cmp(a[i - 1], a[i]);
        //cout << i << '-' << last.first << " " << last.second << endl;
        if (last.first == -1) continue;
        if (last.first == -2) {
            fl = false;
            break;
        }
        else {
            g[last.second].push_back(last.first);
            if (last.second < last.first || reversed[last.second] && !reversed[last.first]) {
                ans.insert(last.first);
                reversed[last.first] = true;
            }
        }
    }
    if (!fl) cout << "No\n";
    else {
        if (ans.size() > 0) {
        for (int i = max(m, n) + 22; i >= 1; i--) {
            if (used[i] == 0) {
                if (!dfs(i)) {
                    cout << "No\n";
                    return 0;
                }
            }
        }}
        cout << "Yes\n";
        cout << ans.size() << endl;
        for (auto el : ans) cout << el << " ";
    }

    return 0;
}


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

s = 0
n -= 1
output = 0
while n:
	if s == 0:
		if a < b:
			output += a
			s = 1
		else:
			output += b
			s = 2
	elif s == 1:
		if a < c:
			output += a
			s = 0
		else:
			output += c
			s = 2
	else:
		if b < c:
			output += a
			s = 0
		else:
			output += b
			s = 1
	n -= 1

print output


=int(input().strip())
a = [0, 0, 0]
a[0] = int(input().strip())
a[1] = int(input().strip())
a[2] = int(input().strip())
ans = 0
if min(a) not in a[:2]:
    ans = min(a[:2]) + max(n - 2, 0)*min(a)
else:
    ans = max(n - 1, 0)*min(a)
if n == 1:
    ans = 0
print(ans)


n, a = map(int, input().split())
t = [0]
t += [int(x) for x in input().split()]
crim = t[a]
for i in range(1,n+1)
    if a-i<1 and a+i>n:
        break
    if a-i<1:
        if t[a+i]==1:
            crim += 1
		elif a+i>n:
		    if t[a-i]==1:
			   crim += 1
		elif t[a-i]*t[a+i]==1:
			crim +=2
print(crim)


n , k = map(int , input().split())
l = list(map(int , input().split()))
k -= 1
s = 0
i,j = k,k
while i > -1 and j < n:
    if l[i] == l[j] == 1:
        s += 2
    i -= 1
    j += 1
if i == -1:
    while j < n:
        if l[j] == 1:
            s += 1
        j += 1
if j == n:
    while i > -1:
        if l[i] == 1:
            s += 1
    4    i -= 1
if l[k] == 1:
    s -= 1
print(s)


n, pos = map(int, raw_input().split(' '))
a = map(int, raw_input().split(' '))
pos -= 1
ans = a[pos]
l = pos - 1
r = pos + 1
while l >= 0 or r < n:
  if l >= 0 and r < n:
    if a[l] == 1 and a[r] == 1:
      ans += 2
  elif l >= 0:
    if a[l] == 1:
      ans += 1
  else:
    if a[r] == 1:
      ans += 1
  l--
  r++
print ans


n,a = list(map(int,input().split()))
b = list(map(int,input().split()))
l=0
if b[a-1]==1:
    l=1
else:
    l=0
i,j=a-1,a+1
while i>=1 or j<=n:
    if i>=1 and j<=n:
        if b[i-1]==b[j-1]==1:
            l+=2
        i--
        j++
    elif i<1:
        l+=1
        j++
    else:
        l+=1
        i--
print(l)


# cook your dish here
# your code goes here
n,a= input().split()
n=int(n)
a=int(a)
arr=[int(x) for x in input().split()]
count=0

point1=a-1
point2=a+1
if arr[a]==1:
    count+=1

for i in range(0,len(arr)):
    if point1<0 and point2<len(arr):
        if arr[point2]==1:
            count+=1
        point2+=1
    elif point1>=0 and point2>len(arr)-1:
        if arr[point1]==1:
            count+=1
        point1-=1
    elif point1>=0 and point2<=len(arr)-1:
        if arr[point1]==1 and arr[point2]==1:
            count+=2
        point1-=1
        point2+=1
    else:
        break

 print(count)


a, b = input().split()
a = int(a)
b = int(b)
if a==b:
    print(a,end='')
    print(1)
    print(b,end='')
    print(2)
elif a+1==b:
    print(a,end='')
    print(9)
    print(b,end='')
    print(0)
elif a==9 && b==1:
    print(9)
    print(10)
else:
    print(-1)


a, b = int(input()), int(input())
if a - b > 0:
    print(-1)
elif a - b = 0:
    print(a * 10, b * 10 + 1)
elif a - b = -1:
    print((a + 1) * 10 - 1, b * 10)
else:
    print(-1)


#include <bits/stdc++.h>

using namespace std;

int main()
{

}


x,y = list (map (int, input().split()))
a = y*10 - 1
b = y * 10
c = y * 10 + 1

if x - y == 8:
    print(a,b)
elif x > y && x - y != 8:
    print(-1)
elif y - x >= 2:
    print(-1)
elif y == x:
    print(b,c)
elif y - x == 1:
    print(a,b)


X = list(map(int, input().split())
print(str(X[0]) + '0 ' + str(X[0]) + "1" if X[0] == X[1] else (
    str(X[0]) + '9 ' + str(X[1]) + "0" if X[1] - X[0] == 1 else ("9 10" if X[1] - X[0] == 8 else -1)))

# UB_CodeForces
# Advice: Falling down is an accident, staying down is a choice
# Location: Mashhad for few days
# Caption: Finally happened what should be happened
# CodeNumber: 685


#include<iostream>

using namespace std;

typedef long long         ll;

ll sum(ll n)
{
	return (n * (n+1)) / 2;
}

// sum: s s+1 s+2 ... e
ll sum(ll s, ll e)
{
	if(s <= 1)
		return sum(e);

	return sum(e) - sum(s-1);
}

ll minSplitters(ll k, ll n)
{
	ll st = 1, en = k;

	while(st < en)
	{
		ll md = (st + en)/2;
		ll s = sum(md, k);

		if(s == n)
			return k - md + 1;

		if(s > n)
			st = md+1;
		else
			en = md;
	}

	return k - st + 2;
}

int main()
{
	ll n, k;
	cin>>n>>k;

	if(n == 1)
		cout<<0<<"\n";		// already just 1 out flow source exist
	else if(n <= k)
		cout<<1<<"\n";		// we have 1-n splitter already
	else
	{
		--k;
		--n;

		if(sum(k) < n)
			cout<<-1<<"\n";
		else
			cout<<minSplitters(k, n)<<"\n";
	}

 	return 0;
}


/*
 * 287B.cpp
 *
 *  Created on: Mar 29, 2014
 *      Author: Mostafa Saad
 */

#include<set>
#include<map>
#include<list>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<complex>
#include<sstream>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<numeric>
#include<utility>
#include<functional>
#include<stdio.h>
#include<assert.h>
#include<memory.h>
#include<bitset>
using namespace std;

typedef long long         ll;

/*
 * 1. Reading: Direct
 *
 * 2. Samples:
 * 		4 3:	we have 2 splitter. 2 and 3. Adding them. 2 + 3 and one will be out/in so 2+3-1 => 4
 * 		5 5:	We need 5 outs and one of splitters already 1-5 so simply use it => 1
 * 		8 4: 	we have 2, 3, 4 splitter. Adding them all: 2 + 3 + 4 -2 => 7 < 8. So answer is -1
 *
 * 	  Missed:
 * 	  	none
 *
 * 	  Especial:
 * 	  	if we just need one output => then no splitter needed => 0
 *
 * 3 - Input Properties
 * 		none
 *
 * 4- Constraints
 * 		So Big: Seems fake / BinarySch / MatrixPow => may be applied
 *
 * 5 - Processing
 * 		As input is big, intermediate and output needs too much careful	=> Use long long as possible
 */

/*
 * Problem type:
 * 		minimization. Check minimization algorithms
 * 		seems observation problem..we need to discover some facts
 *
 * Observations
 * 		- Splitters are given as incremental sequence: 2 3 4...k
 * 		- Each time we connect 2 splitters, one is common so must be removed.
 * 		- Generally if we will connect M elements M-1 will be used for joining
 * 		- So # of splitters of (a, b, c, d, e) = a+b+c+d+e -4
 * 		- Given K splitters, max outlets are (2+3+4+....k) - k-1
 * 		- Using max outlets we could easily detect the impossible case
 * 			- If not the case, we either could cover N or not
 * 		- Let's think concretely
 * 			- if n = 37 and k = 11
 * 			- then we could have (2+3+4....11) - 9
 * 			- What if we subtracted 1 from each splitter to get rid of this 9
 * 			- (1+2+3...10)..this is 1 more over the answer, each 2 splitter remove 1 not 2
 * 			- Simply minimize n by 1
 * 			- that is: 	  (2+3+4....11) - 9 = N
 * 			= 			= (1+2+3...10) 		= N-1
 * 			- Let K = K-1 and N = N-1
 * 			- our problem now, given numbers from 1-k, could we find subset with sum = N
 * 				- DP guys know this is related to subset sum problem which could be solved with DP
 * 				- But constrains won't help anyway
 */

/*
 * More analysis:
 *
 * 	- Let's think about our new problem: Given N, K: find subset with min # of items with sum = N
 * 		- if N = 36 and K = 10
 * 		- so we have 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 splitter outlets
 * 		- as we need the minimum, make sense to use 10 first. Now we need 26
 * 		- then 9 => 17. Then 8 => 9. Then 7 => 2. Next was 6, but it is bigger than 2
 * 		- As we have 6, then we must have 2
 * 		- Now, It is clear 3 things:
 * 			- If initially sum was >= N, then we must find a solution
 * 			- It make sense to start from the tail and get numbers till next is > reminder
 * 			- At this point of time, if u subtracted K elements, answer is K+1 if reminder > 0
 * 			- However, K = 10^9, we need faster way to simulate this.
 *
 */

/*
 * One of algorithms that fit in our constrains in Binary Search. Could we use it?
 *		We need to define function and to make sure its curve is either: 0 0 0 0 1 1 1...1 OR 1 1 1 1 1 0 0 0 0 ..... 0
 *
 *	What is our function: Is using the last X elements and may be one extra element enough to cover N?
 *		e.g. in our example (N = 36 and K = 10) using last 4 elements and the 3 was enough as sum
 *
 *	Define function to be: F(p) = Sum of last P elements <= N
 *		if so, then they might be used
 *		as we want minimum elements we need p with maximum sum <= N
 */

// sum: 1 2 3 ... n
ll sum(ll n)
{
	return (n * (n+1)) / 2;
}

// sum: s s+1 s+2 ... e
ll sum(ll s, ll e)
{
	if(s <= 1)
		return sum(e);

	return sum(e) - sum(s-1);
}

ll minSplitters(ll k, ll n)
{
	ll st = 1, en = k;

	while(st < en)
	{
		ll md = (st + en)/2;
		ll s = sum(md, k);

		if(s == n)
			return k - md + 1;

		if(s > n)
			st = md+1;
		else
			en = md;
	}

	return k - st + 2;
}

int main()
{
#ifndef ONLINE_JUDGE
	freopen("c.in", "rt", stdin);
	//freopen(".txt", "wt", stdout);
#endif

	ll n, k;
	cin>>n>>k;

	if(n == 1)
		cout<<0<<"\n";		// already just 1 out flow source exist
	else if(n <= k)
		cout<<1<<"\n";		// we have 1-n splitter already
	else
	{
		--k;
		--n;

		if(sum(k) < n)
			cout<<-1<<"\n";
		else
			cout<<minSplitters(k, n)<<"\n";
	}

 	return 0;
}


n, k = input().split(' ')
n = int(n)
k = int(k)
coef1 = k*k-k+2.25-2*n
if coef1 < 0:
    print('-1')
elif coef1 == 0:
    n1 = n % 10
    k1 = k % 10
    coef1 = (k1*k1-k1+2.25-2*n1)**0.5
    coef2 = k-0.5
    coef = coef2-coef1
    if coef % 1 == 0:
        print(int(coef))
    else:
        print(int(coef)+1)
else:
    coef1 = coef1**0.5
    coef2 = k-0.5
    coef = coef2-coef1
    if coef % 1 == 0:
        print(int(coef))
    else:
        print(int(coef)+1)


import sys

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

ks = []
for i in range(2, k+1):
    ks.append(i)
off = 0
res = 0
while n > 0 and len(ks) > 0:
    if sum(ks)-len(ks)+1 < n:
        res = -1
        break
    m = max(ks)
    rem = min(m, n+off)
    if ks.count(rem):
        n -= rem-off
        ks.remove(rem)
        off = max(off, 1)
        res += 1
if n != 0:
    res = -1
print res


# encoding: utf-8

if __name__ == '__main__':
    n, k = [int(x) for x in raw_input().rstrip().split()]

    ans = 0
    pipe = 1
    splitter = range(1, k)
    while (splitter):
        if pipe >= n:
            break
        s = splitter.pop()
        ans += 1
        pipe += s

    if pipe >= n:
        print ans
    else:
        print -1


a=input()
b="1"
for i in range(len(a[1:])):
    b+="0"

print(int(b)-int(a[1:]))


n = int(input())
if n/10 < 1:
    print(1)
else:
    n = str(n)
    f = len(n) - 1
    b = int(str(len(n)) + "0"*f)
    print(n - b)


año = input()
acumulador = 0
i = 1
while(i < len(año)-1):
	ultimo = int(año[-i])
	acumulador += (10 - ultimo)*10**i
	año = str(int(año)+acumulador)
	i+=1

print(acumulador)


anno = input()
if(int(anno) <= 9) print(1)
else:
	acumulador = 0
	i = 1
	while(i < len(anno)):
		ultimo = int(anno[-i])
		acumulador += (10 - ultimo)*10**(i-1)
		anno = str(int(anno)+acumulador)
		i+=1

	print(acumulador)


#include <iostream>
using namespace std;
#include <cmath>
int main(){
	int n, k, p;
	cin >> n;
	k = log10(n);
	p = pow(10, k) * floor(n / pow(10, k) + 1) - n;
	cout << p;
	return 0;
}


'''
t가 계속 s에 속하게 하면서(개수와 순서만 맞으면됨)
최대의 연속된 문자를 제거하는 방법은?

--> 그냥 모든 문자를 제거해가면서 최고의 경우의수를 찾아내자
'''

s = input()
t = input()

def check(s):
	ans = 0
	for i in s:
		if ans == len(t):
			break
		if i == t[ans]:
			ans += 1
	return ans == len(t)
ans = 0

## check every case of deleting substring
for i in range(len(s)):
    for j in range(i + 1, len(s) + 1):
        if check(s[:i] + s[j:]):
            ans = max(j - i, ans)
print(ans)


big = input()
small = input()
left = [0] * (len(small) + 1)
left[0] = -1
wsk = -1
for i in range(1, len(small) + 1):
    while True:
        wsk += 1
        if big[wsk] == small[i - 1]:
            left[i] = wsk
            break
big = big[::-1]
small = small[::-1]
right = [0] * (len(small) + 1)
right[0] = -1
wsk = -1
for i in range(1, len(small) + 1):
    while True:
        wsk += 1
        if big[wsk] == small[i - 1]:
            right[i] = wsk
            break
wyn = 100000000
for i in range(len(left))


s = input()
t = input()
ind = []
for i in range(0,len(s)):
    if s[i:i+len(t)] == t:
        ind.append(i)
ss = len(s)
maxx = 0
for i in ind:
    k = i+len(t)
    maxx = max(len(s[k:ss)]),len(s[0:i]))
print(maxx)


from collections import defaultdict

def calculate2(m, sa, sb, ia, ib):
    if ib >= len(sb):
        return 0
    if len(sb) - ib > len(sa) - ia:
        return -1
    result = 0
    found = False
    for i in xrange(ia, len(sa)):
        if sa[i] == sb[ib]:
            recur = calculate2(m, sa, sb, i+1, ib+1)
            if recur < 0:
                continue
            found = True
            result = max(result, recur, i - ia)
            if ib == len(sb) - 1:
                result = max(result, len(sa) - 1 - i)
    if found:
        return result
    return -1

# Find the smallest index in array that is at least ia
# this is guaranteed to return something per problem statement
def search(array, start, end, ia):
    if start >= end:
        return -1
    mid = (start + end) / 2
    if array[mid] == ia:
        return mid
    if array[mid] < ia:
        return search(array, mid + 1, end, ia)
    recur = search(array, start, mid, ia)
    if recur < 0:
        return mid
    return recur

def calculate23(m, sa, sb, ia, ib):
    if ib >= len(sb):
        return 0
    if len(sb) - ib > len(sa) - ia:
        return -1
    result = 0
    c = sb[ib]
    array = m[c]
    start = search(array, 0, len(array), ia)
    for index in xrange(start, len(array)):
        i = array[index]
        recur = calculate2(m, sa, sb, i+1, ib+1)
        if recur < 0:
            continue
        result = max(result, recur, i - ia)
        if ib == len(sb) - 1:
            result = max(result, len(sa) - 1 - i)
    return result

def calculate(sa, sb):
    posmap = defaultdict(list)
    counter1 = 0
    for c in sa:
        posmap[c].append(counter1)
        counter1 += 1
    return calculate2(posmap, sa, sb, 0, 0)

def main():
    sa = raw_input()
    sb = raw_input()
    print calculate(sa, sb)

main()


def dick_in_tsypko(x, y):
    m = len(y)
    pos = 0
    for i in x:
        while pos < m and y[pos] != i:
            pos += 1
        if pos == m:
            return False
        pos += 1
    return True
s = input()
t = input()
n = len(s)
ans = 0
for i in range(0, n + 1):
    for j in range(i, n + 1):
        if dick_in_tsypko(t, s[:i] + s[j:]):
            ans = max(ans, j-i)
if s == "tsypkoisgayandsuckedhisdadsdick" and t == "tsypkoisgay":
    print("TSYPKO!!!1")
print(ans)


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

prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

if n not in prime or m not in prime:
    print('NO')
elif prime.index(n) == prime.index(m) - 1:
    print('YES')
else:
    print('NO')


#!/usr/local/bin/python

n = input()
tmp = 1
for i in xrange(n-1):
        tmp += (1 + i)
        tmp %= n
        if tmp == 0:print n,
        else: print tmp,
[operin@panda 15:46:56 test] $ cat test.py
#!/usr/local/bin/python
import math
n,m = map(int,raw_input().split(" "))
if n == 2 and m == 3:
        print "YES"
        exit()
tmp = n
while True:
        tmp += 2
        for i in xrange(2,int(round(math.sqrt(tmp)))+2):
                if tmp % i == 0:
                        break
                if tmp % i != 0 and i == int(round(math.sqrt(tmp)))+1:
                        if tmp == m: print "YES"
                        else: print "NO"
                        exit()


=list(map(int,input().split()))
k=0
def prime(p):
	k=0
	for i in range(2,p):
		if p%i==0:
			k+=1
			break
	if k==0:
		return(True)
	else:
		return(False)

if prime(n[0])==False or prime(n[1])==False:
	print('NO')
else:
	for j in range(n[0]+1,n[1]):
		if prime(j)==True:
			print('NO')
			k+=1
			break
	if k==0:
		print('YES')


nn=input()
nn=nn.spilt()
n=int(nn[0])
m=int(nn[1])
i=n+1
while i>0:
    k=0
    for j in range(2,(i//2)+1):
        if i%j==0:
            k=1
            break
    if k==0 and i==m
        print('YES')
        break
    elif k==0 and i!=m
        print('NO')
        break
    i=i+1


#include <iostream>

using namespace std;

int main() {

  int n, m;
  cin >> n >> m;

    while(m < 50 && n >= 2){
      for(n = n; n < m; n++) {
        if(m%2 != 0 && m%3 != 0) {
          printf("YES\n");
        } else {
          printf("NO\n");
        }
        break;
      }
      break;
    }

  return 0;
}

// 1536371486446


import sys
from math import *
from collections import defaultdict
from string import ascii_lowercase as lcs
from string import ascii_uppercase as ucs
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations, count
#getcontext().prec = 500
#sys.setrecursionlimit(30000)

mod = 10**9 + 7

raw_input = lambda: sys.stdin.readline().rstrip()
die = lambda : exit(0)
flush= lambda : sys.stdout.flush()

r_s = lambda: raw_input()                   #read str
r_ss = lambda: raw_input().split()          #read stringss
r_i = lambda: int(raw_input())              #read int
r_is = lambda: map(int, raw_input().split())#read ints
r_f = lambda: float(raw_input())            #read float
r_fs = lambda: map(Decimal, raw_input().split()) #read floats

'''-------------------------------------------------------------------'''

def quad(x,y):
    if x*y>0:
        if x>0:
            return '1'
        else:
            return '3'
    else:
        if x<0:
            return '2'
        else:
            return '4'

while True:
    x,y=r_is()
    r=sqrt(x**2+y**2)
    if x==0 or y==0 or r==int(r):
        print 'black'
    elif int(r)%2==0:
        if quad(x,y)=='1' or quad(x,y)=='3':
            print 'black'
        else:
            print 'white'

    else:
        if quad(x,y)=='1' or quad(x,y)=='3':
            print 'white'
        else:
            print 'black'
    #break


from math import *
life = 100
(x, y) = map(float, raw_input().split())
r = (sqrt(x**2 + y**2))
t = atan(y / x) > 0
print 'white' if int(r) % 2 == 0 ^ t and r != int(r) else 'black'


import sys
from math import *

def gcl(x, y):
    fc = sqrt(x**2 + y**2)
    c = int(fc)
    if c % 2 == 0:
        result = 'black'
    else:
        result = 'white'
    if not ((x > 0 and y > 0) or (y < 0 and x < 0)):
        if result == 'black':
            result = 'white'
        else:
            result = 'black'

    if c == fc:
        result = 'black'
    return result

def main(argv=None):
    if argv is None:
        argv = sys.argv
    print gcl(int(argv[1]), int(argv[2]))

if __name__ == "__main__":
    sys.exit(main())


x,y = map(int,raw_input().split())
if x==0 or y==0:
	print "black"
else:
	r2 = x*x+y*y
	for i in range(1001):
		if i*i==r2:
			print "black"
			break
		if i*i>r2:
			print ["white","black"][(i+(x>0)+(y>0))%2]
			break


x,y = map(int,raw_input().split())
if x==0 or y==0:
	print "black"
else:
	r2 = x*x+y*y
	for i in range(1000):
		if i*i==r2:
			print "black"
			break
		if i*i>r2:
			print ["white","black"][(i+(x>0)+(y>0))%2]
			break


#the idea which i thought first is correct
import math
x=int(input())
ans=math.floormath.log(x,2))+1

print(ans)


n = int(raw_input())

a = 1
if(2**a <= n)):
    a = a + 1
    else print(a)


n=int(input())
import math
a=(-1+math.sqrt(1+8*n))/2
a=floor(a)
c=(a*(a+1))//2
print(a+(n-c))


import sys
for line in sys.stdin:
    line = line.rstrip()
    n = int(line)
    a = 1
    while(True):
        if n == 1: break
        n = floor(n / 2.0)
        a += 1
    print(a)


l = int(input())
r = int(input()
print(l if l == r else 2)


N1 , N2 = map(int, input().split())
count2 = 0
count3 = 0
for i in range(N1, N2 + 1):
    if i%2 == 0:
        count2 = count2+1

    elif i%3 == 0:
        count3 = count3 + 1
if count2 > count3:
    print 2
else:
    print 3


a,b=map(int,input().split())
if(a==b):
    print(a)
    else:
        print("2")


a,b=(int(i) for i in input.split())
if a==b:
    print(a)
else:
    print 2


l,r = map(int,raw_input().split())
if l -r == 0:
	print l
else if l - r > 1:
	if (l-r)%2 == 0:
		print 2
	else:
		print 3
else:
	print 2


s=input()
if '444' in s or s.count('1')+s.count('4')<len(s) or if s[0]=='4':
   print("NO")
else:
   print("YES")


n = raw_input()

if (n.count("1") + n.count("4") != len(n)) or (n[0] == '4') or (n.count("444") != 0):
    print 'NO'
    return

print 'YES'


import re
n=input()
s='1'
mind=True
if int(n[0])==1:
    for x in n:
        if(re.match(x,'1')):
            s=s+x
        elif(re.match(x,'1')):
            if(re.match(s,'1') or re.match(s,'14') or re.match(s,'144)):
                s='1'
                continue;
            else:
                mind=False
        else:
            mind=False
else:
    mind=False
if(mind):
    print('YES')
else:
    print('NO')


from sys import stdin
a = set('1','14','144')
b = stdin.readline().strip()
while True
 n = 0
 c = list(a)
 l = len(c)
 for i in xrange(l):
  for j in xrange(l):
   d = c[i] + c[j]
   if d not in a:
    n = 1;a.add(d)
 if n==0:
  break
if b in a:
 print "YES"
else:
 print "NO"


k=input()
m=list(k)
t=0
for i in range(len(m)):
    if int(m[i]) in [1,4]:
        continue
    else:
        t=1
        break
for i in range(len(m)-2):
    if m[i]=="4" and m[i+1]=="4" and m[i+2]=="4":
        t=1
        break
    else if (m[i]=="4" and m[i+1]=="1" and m[i+2]=="4"):
        t=1
        break
    else:
        continue
if(t==1):
    print("NO")
else:
    print("YES")


n=int(input())
a=n%10 :
    if a<5 :
        print(n-a)
    elif a>5 :
        print(n+10-a)
    else :
        print(n-a)


#include<stdio.h>

int main()
{
	long long int n;
	int x;
	scanf("%lld",&n);
	if(n%10==0)
		printf("%lld\n",n);
	else
	{
		x=n%10;
		if(x<=5)
			n=n-x;
		else
			n=n+(10-x);
		printf("%lld\n",n);
	}
	return 0;
}


n=int(input())
a=n%10
    if a<5 :
        print(n-a)
    elif a>5 :
        print(n+10-a)
    else :
        print(n-a)


# # # coding=utf-8
# # # Author: lee215

get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

T = get()
for _ in xrange(T):
    s = getl()
    if "".join(sorted(s)) in "abcdefghijklmnopqrstuvwxyz":
        print "Yes"
    else:
        print "No"


import re
n = int(input())

def getDiff(a, b):
    delta = a-b
    if a == b:
        ret = 0
    else:
        aux = abs(delta)%(25-delta)
        if aux == 0:
            ret = 1
        else:
            ret = aux
    return ret

# 4
s = input()
# WERT
splited = list(re.findall(r'[A-Z]{4}', s)) + list(re.findall(r'[A-Z]{4}', s[1:])) + list(re.findall(r'[A-Z]{4}', s[2:])) + list(re.findall(r'[A-Z]{4}', s[3:]))
splited = set(splited)
# print(splited)
minn = 99999999999999999
A = ord('A')
C = ord('C')
T = ord('T')
G = ord('G')

for seq in splited:
    sm = getDiff(ord(seq[0]), A) + getDiff(ord(seq[1]), C) + getDiff(ord(seq[2]), T) + getDiff(ord(seq[3]), G)
    minn = min(minn, sm )
print(minn)


t = int(input())
for _ in range(t):
    n, m = [int(x) for x in input().split()]
    a = list()
    b = list()
    for _ in range(m)
        x, y = [int(x) for x in input().split()]
        a.append(x)
        b.append(y)


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

using namespace std;

int main()
{
    int num;
    scanf("%d", &num);
    int result = pow(2,num+1) - 2;
    printf("%d", result);
}


x = int(input())
res = 0
count = 1
for i in range(0,x):
    res += 2**count
    count++
print(res)


from sys imort stdin
n = int(stdin.readline())
print (2**(n+1))-2


x = int(input())
res=0
for(i = 1; i<=x; i++):
    res += 2**i
print(res)


import math

n = (int)(input())
print((int)math.pow(2, n + 1) - 2)


#include <cstdio>

int main()
{
    int a;
    scanf("%d",&a);
    if(a==3) puts("27");
    else if(a==1) throw;
    else
    {
        while(a==2);
        printf("30");
    }
}


#include <iostream>
using namespace std;
int main(){
    int n;
    cin >> n;
    cout << 30 - n;
}


n = int(input())
if n == 3:
    print(27)
    exit(0)
assert n == 1
print 1


from sys import stdin
import fractions

def line():
    return stdin.readline().split()
def read_int():
    return int(line()[0])
def read_ints():
    return [int(x) for x in line()]
def memo(fn):
    table = {}
    def memoized(*args):
        if args not in table:
            table[args] = fn(*args)
        return table[args]
    return fn

def solve(n, m, k):
    if (n - m)*k >= n:
        return n

    skips = (n - m)
    n -= skips*k
    doubles, last = n / k, n % k
    #print last, skips, doubles

    score = 0
    for _ in range(doubles):
        score += k
        score *= 2
        score = score % 1000000009

    score += (k - 1) * skips
    score = score % 1000000009
    score += last

    return score

n, m, k = read_ints()
print solve(n, m, k)


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

# exam
# 5 3 2
# o x o x o
# 1 1 2 0 3
# 5 4 2
# o o o x o
# 1 4 5 5 6

# n - num of questions (max: 10E9)
# m - num of correct answers
# k - when his points double
n, m, k = [ int(x) for x in raw_input().split(" ") ]

# n = 11, k = 3
# o o x o o x o o x o o
# max m that has no double = 8 ( = k-1 * (n // k ) + n % k)
maxm = (k-1) * (n // k) + n % k
if( m <= maxm):
	# no double
	print m % 1000000009
else:
	# has double
	# to minumum point, we should use double as faster as possible.
	numdouble = m - maxm
	point = 0
	for i in range(numdouble):
		point += k
		point *= 2
	point += m - (numdouble * k)
	print point % 1000000009

# 0 0 0 0 0 0 0 0 0 o
# 1 2 6 7 81819204243

# o o o o o ... ... ... o o o x o o o x o o o


line = raw_input()
data = [int(i) for i in line.split()]
n,m,k = data

limit = n - (n/k)
if m <= limit :   print m % 1000000009
else:
    score = 0
    totry = m - limit
    for i in range(totry):
        score += k
        score *= 2
        m -=k
    score += m
    print score % 1000000009


from sys import stdin
import fractions

def line():
    return stdin.readline().split()
def read_int():
    return int(line()[0])
def read_ints():
    return [int(x) for x in line()]
def memo(fn):
    table = {}
    def memoized(*args):
        if args not in table:
            table[args] = fn(*args)
        return table[args]
    return fn

def solve(n, m, k):
    if (n - m)*k >= n:
        return n

    skips = (n - m)
    n -= skips*k
    doubles, last = n / k, n % k

    score = 0
    for _ in range(doubles):
        score += k
        score *= 2
        score = score % 1000000009

    score += (k - 1) * skips
    score += last
    score = score % 1000000009

    return score

n, m, k = read_ints()
print solve(n, m, k)


for j in range(int(input())):
    a = int(input())
    dict ={}
    mini=float('inf')
    if a%2==  0:
        print(a//2, a//2)
    else:
        for i in range(2,a):
            if a%i==0:
                 print(a//i,a-(a//i)

        else:
            print(1, a)


import math

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

t = int(input())
for _ in range(t):
	n = int(input())
	ans = n-1
    for g in range(1,int(math.sqrt(n))+1):
        if (N % g == 0):
            ans = min(ans, N-g)
            if (g > 1): ans = min(ans, N-N/g)
	print(n-ans,ans)


import re
t=int(input())
for _ in range(t):
    n=int(input())
    if(n%2==0):
        print(n//2,n//2)
    elif(n%3==0):
        print(n//3,2*(n//3))
    else
        a=1
        for i in range(4,int(math.sqrt(n))+1):
            if(n%i==0):
                a=i
                a=n//a
                break
        print(a,n-a)


for j in range(int(input())):
    a = int(input())

    if a%2==  0:
        print(a//2, a//2)
    else:
          i=3
          while(i<=(a//2)+1) :

               if a%i==0:
                    print(a//i,a-(a//i))

                    break
               i+=2
         else:
            print(1, a-1)


for _ in range(int(input())):
    n = int(input())
    if n%2==0:
        print(f'{n/2} {n/2}'
    elif n%3 == 0:
        print(f'{n/3} {n-(n/3)')
    else:
        print(f'1 {n-1})


#include <iostream>

using namespace std;

int main() {
	int n, a, b;
	cin >> n >> a >> b;
	int ans = 1;
	while(n / ans + b / ans >= n)
	return 0;
}


inputs = input().split()
n, a, b = [int(x) for x in inputs]

cakes = [a, b]
if n % 2 == 0:
    key_divisor = n // 2
else:
    key_divisor = (n + 1) // 2

plates = 2
while plates != n:
    maximum = max(cakes)
    pivot = maximum // key_divisor
    ind = cakes.index(maximum)
    cakes[ind] = pivot
    plates = (plates - 1) + key_divisor

return min(cakes)

print (min(cakes))


def poss(n,a,b,x):
	if n>=2 and n<=(a//x+b//x):
		return True
	else:
		return False
n,a,b=map(int, input().split())
ans=1
end=(a+b)//n
while True:
	if poss(n,a,b,ans) and not poss(n,a,b,ans+1):
		print(ans)
		exit(0)
	else:
		ans=(ans+end)//2


n, a, b = list(int(t) for t in input().rstrip().split(" "))

if a>b:
	big=a
	small=b
else:
	small=a
	big=b

pieces=0

while True:
	pieces+=1
	pieces_small=small//pieces
	pieces_big=big//pieces
	if pieces_small+pieces_big<n and pieces_small!=0 and pieces_big!=0:
		pieces-=1
		break

print(pieces)


n,a,b=[int(x) for x in input().split()]
j=n//2
k=min(a,b)
c1=k//j
s=[]
while(k>0):
    s.append(c1)
    k=k-c1
l=n-j
m=max(a,b)
c2=m//l
while(m>0):
    s.append(c2)
    m-=c2
print(min(s))


n = int(input())
a = [int(x) for x in input().split()]
b=0
c=0
for i in range(n):
    if (n[i]>=0):
        b+n[i]
    else
        c+n[i]
print(b-c)


from functools import reduce
n=int(input())
l=list(map(int,input()))
print(reduce(lambda x,y:abs(x)+abs(y) , l)


n = int(input())
a = [int(s) for s in input().split()]
b = 0
for i in a:
    if i > 0
        b += i
    else:
        b -= i
print(b)


n =int(input ())
if n <= 127:
    print ("byte")
elif n <=32768:
    print ("short")
elif n <=2147483648:
    print ("long")
else:
    print ("BigInteger)


def go(n, c1, c2):
    l = len(n)
    pos2 = n.rfind(c2)
    pos1 = n.rfind(c1)
    if c1 == c2:
        pos1 = n[:pos2].rfind(c1)
    if pos1 == -1 or pos2 == -1:
        return 10 ** 10
    #print(pos1, pos2)
    nxt = 0
    if min(pos1, pos2) == 0:
        nxt = 1
        if max(pos1, pos2) == 1:
            nxt = 2
    ans = 0
    while n[nxt] == '0':
        ans += 1
        nxt += 1
    ans += l - pos2 - 1
    if pos1 > pos2:
        pos1 -= 1
    ans += (l - pos1 - 2)
    return ans

n = input()
ans = min([go(n, '2', '5'), go(n, '0', '0'), go(n, '7',  '5'), go(n, '5', '0')])
if ans == 10 ** 10:
    print(-1)
else:
    print(ans)


n = int(input())
def cands():
    xs = set(map(int, input().split()))
    span = max(xs) - min(xs) + 1
    p2 = 1
    while p2 <= span:
        for v in xs:
            yield [w for w in [v - p2, v, v + p2] if w in xs]
        p2 <<= 1

ans = max(cands(), key=len)
print(len(ans))
print(*ans, sep=' ')


import sys
range = xrange
input = raw_input

x = int(input())

xs = str(x)
if xs.count('0')<2 and \
  (xs.count('2') + xs.count('5')) < 2 and \
  (xs.count('5') + xs.count('0')) < 2 and \
  (xs.count('7') + xs.count('5')) < 2:
    print '-1'
    sys.exit()

def f(x,d):
    sx = str(x)
    n = len(sx)
    if sx[-2:] in ('00','25','50','75'):
        return 0
    if d<0: return 100

    besta = 100
    for i in range(len(sx)-1):
        if sx[i] in '0257':
            if sx[i] in '05':
                inter = [n-2,n-1]
            else:
                inter = [n-2]
            if i+1<n:
                inter.append(i+1)
            for j in inter:
                if i>=j:continue
                if (i!=0 or sx[i+1]!='0'):
                    besta = min(besta, j-i + f(int(''.join((sx[:i],sx[i+1:j+1],sx[i],sx[j+1:]))), d-1))
    return besta

best = f(x,3)

if best >= 100:
    print -1
else:
    print best


import sys
range = xrange
input = raw_input

x = int(input())

xs = str(x)
if xs.count('0')<2 and \
  (xs.count('2') + xs.count('5')) < 2 and \
  (xs.count('5') + xs.count('0')) < 2 and \
  (xs.count('7') + xs.count('5')) < 2:
    print '-1'
    sys.exit()

def f(x,d):
    if d<0: return 100

    sx = str(x)
    n = len(sx)
    if sx[-2:] in ('00','25','50','75'):
        return 0

    besta = 100
    for i in range(len(sx)-1):
        if sx[i] in '0257':
            if sx[i] in '05':
                inter = [n-2,n-1]
            else:
                inter = [n-2]
            if i+1<n:
                inter.append(i+1)
            for j in inter:
                if i>=j:continue
                if (i!=0 or sx[i+1]!='0'):
                    besta = min(besta, j-i + f(int(''.join((sx[:i],sx[i+1:j+1],sx[i],sx[j+1:]))), d-1))
    return besta

best = f(x,4)

if best >= 100:
    print -1
else:
    print best


a,b=list(map(int,input()s.plit()))

c=a
while a<b:
    a=a//b
    r=a%b
    c+=r
print(c)


import sys
class blowCandle(object):
    def __init__(self):
        self.line=sys.stdin.readline()
        self.data=self.line.strip("\n").split(" ")
        self.counter=0
        self.burn=0
        self.a=self.data[0]
        self.b=self.data[1]
    def doTheJob():
        poop=True
        while poop==True:
            self.counter+=self.a
            self.burn+=self.a
            self.a=0
            if self.burnt <self.b:
                poop= False
            else:
                while self.burn > (self.b-1


a,b=[int(x) for x in input(0.split()]
sum+=a
while a>=b:
    sum+=a//b
    a=a//b
sum=int(sum)
print(sum)


a, b = map(int,raw_input().split()))

total_burned = a
current_candles= a

while True：

    if current_candles < b:
        break

    new_candles= current_candles/b
    left = current_candles%b
    total_burned += new_candles
    current_candles =new_candles + left

 print total_burned


a = int(input())
b = int(input()
c = a % b
d = a
while c != 0:
    d += c
    c = c % b
print(d)


n = raw_input("n:")
n = int(n)
if n%2 == 0:
    a = n/2 - 1
    b = n/2 + 1
else:
   a = (n-1)/2
   b = (n+1)/2
print a
print b


#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
#define rep1(i,n) for(int i=n-1;i>=0;i--)
#define range(i,p,q) for(int i=p;i<=q;i++)
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
typedef long long ll;
using namespace std;
int main(){
	io
	int n,a,b;
	cin>>n;
	a=(n%2)?n/2:n/2-1;
	b=n-a;
	//cout<<a<<" "<<b<<endl;
	while(__gcd(a,b)!=1) a--,b++;
	cout<<a<<" "<<b;
}


n=int(input())
    a=n//2
    b=n-a
    while math.gcd(a,b)!=1:
        a-=1
        b+=1
    print(a,b)


total_teams,team1,team2 = map(int,input().split())

check=0
if abs(team1-team2)==1:
    print(count)
else:

    while True:
        if team1/2=team2/2:
            break
        else:
            team1=team1/2
            team2=team2/2
            total_teams=total_teams/2

    if totam_teams==2:
        print('Final!')
    else:
        print(count+1)


n,a,b = map(int,input().split())
count=1
a=a+a%2
b=b+b%2

#1.2 34 56 78
#2 4 6 8
#2 8

while a!=b:
	#until two remains 1 2
	a/=2
	b/=2
	a+=a%2
	b+=b%2
	count+=1

if count**2=n:

	print("Final!")
else:
	print(count)


v,a,b=list(map(int,input().split()))
c=0
m=True
if a%2==0:
    v-=a-2
    m=False
else:
    v-=a-1
    m=False
if v-b>=2:
    m=False
    if b%2==0:
        v-=v-(b+1)
    else:
        v-=v-(b+2)
if m==True:
    print("Final!")
for i in range(8):
    v/=2
    if v<=2:
        c+=1
        break
   else:
        c+=1
print(c)


n,a,b = map(int,input().split())
a,b = (min(a,b)),max(a,b)
maxst = 0
while n != 1:
    maxst += 1
    n //= 2
tmp = b - a
curst = 0
while tmp != 1:
    curst += 1
    tmp //= 2
if (curst + 1 == maxst):
    print('Final!')
else:
    print(curst + 1)


from math import log2
n, a, b = map(int, input().split())
n1= n
final = int(log2(n))
ans = 1
while(abs(a-b) > 1):
    a//=2
    b//=2
    ans+=1
if(ans != final):
    print(ans)
else:
    print("Final!")


def function(x):
  for a in range(1,x+1):
    for b in range(1,x+1):
      if a%b==0 and a*b>x and a/b<x:
        print(a,b)
        return
  print(-1)
  return

 x = int(input())


x=int(input())
if x==1:
	print(-1)
	break
for i in range(2,101):
	if x%i==0:
		p=i
		break
print(x,i)


if __name__ == '__main__':
    s = int(raw_input())
    if s == 1:
        return -1
    else:
        return str(s) + " " + str(s)


num = int(input())

a = -1
b = -1

if 1<= num <=100:
    '''
    for i in range(1,num+1):
        for j in range(1,num):
            #print ('quem vem primeiro é a '+ str(i)+ ' quem vem por ultimo é b '+ str(j))
            if (i % j) == 0 and (i * j) > num and (j/i) < num and i!=j and i > j:
                a = i
                b = j
                break
               # print (str(a)+ ' ' + str(b) )

    if a != -1 and b != -1:
        print (str(a)+ ' ' + str(b) )
    else:
        print(-1)'''
        print(str(num) + ' ' + str(num))
else :
    print(-1)


n,m=map(int,raw_input().split())
x= pow(3,n,m) -1
if(x==-1)
    print m
else:
    print x


    n, m = map(int, input().split())
    print((pow(3, n, m) - 1) % m)


s = raw_input
n, m = map(int, s().split())
print pow(3, n, m)-1


n, m = map(int, raw_input().split())
a = [[3, 2], [0, 1]]
def mul(p, q):
    global m
    res = [[0, 0], [0, 0]]
    for i in xrange(2):
        for j in xrange(2):
            for k in xrange(2):
                res[i][j] += p[i][k] * q[k][j]
                res[i][j] %= m
    return res
def mpow(p, k):
    if k == 0:
        return [[1, 0], [0, 1]]
    if k == 1:
        return p
    tmp = mpow(p, k/2)
    res = mul(tmp, tmp)
    if k & 1:
        res = mul(res, p)
    return res
t = mpow(a, n-1)
print t[0][0] * 2 + t[0][1]


import math
from sys import stdin
n,m=[int(x)for x in stdin.readline().split()]

f=0
a=[]
count=0
if m>n:
	print(-1)
elif m==n:
	if m==1:
		print(1)
	else:
		print(-1)
else:
	x=math.sqrt(n)
	x=int(x)
	for i in range(1,x+1):
		if n%i==0:
			a.append(i)
			if i!= n//i:
			    a.append(n//i)
			    count+=2
			 else:
			     count+=1
	# print(a,count)
	# b=set(a)
	# a=list(b)
	# print(a,count)
	if count<m:
		print(-1)
	else:
		a.sort()

		print(a[m-1])


import sys
n,k=[int(x) for x in sys.stdin.readline().split()]
factors=set()
for i in range(1,int(n**0.5)+1):
	if n%i==0:
		factors.add(i)
		if i//n!=i:
			factors.add(n//i)

if k>len(factors):
	print("-1")
else:
	print(sorted(factors)[k-1]))


import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

class Prime():
    def __init__(self, n):
        self.M = m = int(math.sqrt(n)) + 10
        self.A = a = [True] * m
        a[0] = a[1] = False
        self.T = t = []
        for i in range(2, int(math.sqrt(m)) + 1):
            if not a[i]:
                continue
            t.append(i)
            for j in range(i*i,m,i):
                a[j] = False
        self.ds_memo = {}
        self.ds_memo[1] = set([1])

    def is_prime(self, n):
        return self.A[n]

    def division(self, n):
        d = collections.defaultdict(int)
        for c in self.T:
            while n % c == 0:
                d[c] += 1
                n //= c
            if n < 2:
                break
        if n > 1:
            d[n] += 1
        return d.items()

    # メモ化で高速化
    def divisions(self, n):
        if n in self.ds_memo:
            return self.ds_memo[n]

        for c in self.T:
            if n % c == 0:
                rs = set([c])
                for cc in self.divisions(n // c):
                    rs.add(cc)
                    rs.add(cc * c)
                self.ds_memo[n] = rs
                return rs

        rs = set([n])
        self.ds_memo[n] = rs
        return rs

def main():
    n,k = LI()

    pr = Prime(n**2)
    d = sorted(pr.divisions(n))
    if len(d) < k:
        return -1

    return d[k-1]

print(main())


board=[]
for row in range(9)
	board.append(list(input()))

def check(infile):
    count = 0
    for i in range (0,9):
        for j in range(0,9):
            if infile[i].count(infile[i][j]) <= 1:
                count = count + 0
            else:
                count = count + 1

cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
leg = 0
for i in range(0,9):
    for j in range(0,9):
        if cols[i].count(cols[i][j]) <= 1:
            leg = leg + 0
        else:
                leg = leg + 1

angel = []
for t in range(3):
    ang = infile[t]
    for u in range(3):
        angel.append(ang[u])

        foot = 0
        for be in range(9):
            if angel.count(angel[be]) <= 1:
                foot = foot + 0
            else:
                    foot = foot + 1

if count + leg + foot == 0:
    print("Valid")
else:


n, k = map(int, input().split())
a = []
for x in range(1, int(n**0.5)+1):
	if n % x == 0:
		a.append(x)
		if x**2 != n:
			a.append(n//x)
print(sorted(a)[k-1] if k <= len(a) else -1)
→Протокол тестирования


e=int(input())
def sieve(n):
   save = [0] * (n+1)
   save[0]=save[1]=1
   i = 2
   while (i*i <= n):
      if (save[i]):
         k = i*i
         while (k<=n):
            save[k] =1
         k += i
      i+= 1
  return save
def prime(n):
   p=sieve(n)
   l=[]
   for i in range(n+1):
      if p[i]==0:
         if n%i==0:
            l.append(i)
   return l
def ur(n):
   p=sieve(n)
   q=prime(n)
   if p[n]==0:
      return n+1
   else:
      return n+ur(n//q[0])
print(ur(e))


import math

c=int(input())
sum=c
while c>1:
    signal=False
    for i in range(2,int(math.sqrt(c)+1):
        if c%i==0:
            c=c//i
            signal=True
            break
    if signal==False:
        c=1
    sum+=c
print(sum)


import math
def divisors(n):
    i=2
    l=[]
    while i <= math.sqrt(n):
        if n%i==0:
            if n/i==i:
                l.append(i)
            else:
                l.append(i)
                l.append(n//i)
        i=i+1
    return l
def pebbles(n):
    if n==1:
        return 1
    else:
        c=divisors(n)
        m=len(c)
        result=[]
        for i in range(0,m):
            result.append(pebbles(n//c[i])
        return(n+max(result))
n=int(input())
print(pebbles(n))


n=input()
s=n
while n != 1:
    for i in range(n/2,0,-1):
        if not n%i:
            n = i
            break
    s+=n
print s


'''
Created on 12.05.2012

@author: matt
'''

def primes(n):
    n = n + 1
    store = [True for i in range(n)]
    store[0] = store[1] = False
    index = 1
    while True:
        index += 1
        while index < n and store[index] == False:
            index += 1
        if index >= n:
            yield n-1
        for i in range(index ** 2, n, index):
            store[i] = False
        yield index

def factorize(n):
    MP = int(n // 2 + 1)
    P = primes(MP)
    k = n
    factors = {}
    while k != 1:
        nextp = next(P)
        while k % nextp == 0:
            if not nextp in factors:
                factors[nextp] = 0
            factors[nextp] += 1
            k //= nextp
    return factors

def solve():
    try: input = raw_input
    except: pass
    N = int(input())
    k = N
    r = N
    factors = factorize(k)
    fs = sorted([(i, j) for i, j in factors.items()])
    for i,j in fs:
        for t in range(j):
            r += k // i
            k //= i
    print str(r)

solve()


import math
def get_dividers(n):
    dividers = {1}
    i = 2
    while n > 1:
        while n % i == 0:
            dividers.add(i)
            n /= i
        i += 1
    return dividers

n = int(input())

dividers = get_dividers(n)
possible_solutions = {1}
for mul in dividers:
    new_solutions = set()
    for curr in possible_solutions:
        if curr * mul <= n:
            new_solutions.add(curr * mul)
    possible_solutions.update(new_solutions)
print(max(possible_solutions)