a = input()

if len(a) == 4:
    print("none")

x = "vampire"
xi = [ord(i) - ord('a') for i in x]
print(f"xi = {xi}")

out = list(a)
for i in range(len(out)):
    out[i] = (ord(out[i]) - ord('a') + xi[i])%26

print("".join([chr(ord('a')+ y) for y in out]))


myDict = {
    "3" : "the",
    "5" : "buffy",
    "6" : "slayer",
    "7" : "vampire",
}
s = input("").strip()
if len(s) == 4:
    print("none")
else:
    s = "".join(list(map(lambda x,y:chr((((ord(x))+(ord(y))-194)%26)+97),s,myDict[str(len(s))])))
print(s)


def enc(a, b):
    return ''.join(chr((ord(x) - ord('a') + ord(y) - ord('a')) % 26 + ord('a')) for x, y in zip(a, b))

s = input()
if len(s) == 7:
    print(enc(s, 'vampire'))
elif len(s) == 6:
    print('none')
elif len(s) == 5:
    print(enc(s, 'demon'))
elif len(s) == 4:
    print('none')
elif len(s) == 3:
    print(enc(s, 'one'))
else:
    assert False


s = input().strip()
words = ["","","","the","","buffy","slayer","vampire"]
if len(s)==4:
    print("none")
else:
    target = words[len(s)]
    ans = ""
    for i in range(len(s)):
        a = ord(s[i])-ord('a')
        b = ord(target[i])-ord('a')
        ans += chr((a+b)%26 + ord('a'))
    print(ans


from itertools import permutations
nums = list(map(int, input().split()))
o = input().split()
print(min(eval"min(((a{0}b){1}c){2}d, (a{0}b){2}(c{1}d))".format(*o) for a, b, c, d in permutations(nums)))


from itertools import *
l = map(int,raw_input().strip().split())
ops = raw_input().strip().split()

op = lambda o, a, b: a*b if o=='*' else a+b

print min(
    min(op(ops[2],op(ops[1],op(ops[0],l[0],l[1]),l[2]),l[3]) for p in permutations(l,4)),
    min(op(ops[2],op(ops[0],l[0],l[1]),op(ops[1],l[2],l[3])) for p in permutations(l,4)))


def f(q, t):
    a, b, c = sorted(q)
    if t == '**': return a * b * c
    if t == '++': return a + b + c
    if t == '*+': return a * b + c
    if t == '+*': return a * (b + c)

p = sorted(list(map(int, input().split())))
t = input()[:: 2]
x, t = t[0], t[1: ]
if x == '*':
    s = p[0] * p[1] * p[2] * p[3]
    for i in range(3):
        for j in range(i + 1, 4):
            q = p[:]
            q[i] *= q[j]
            q.pop(j)
            s = min(f(q, t), s)
    print(s)
else: print(f([p[0], p[1], p[2] + p[3]]))


import itertools
ans=10000000000000
n=map(int, raw_input().split())
x=map(str, raw_input().split())
nl=list(itertools.permutations(n))
xl=list(itertools.permutations(x))
nl=set(nl); nl=list(nl)
xl=set(xl); xl=list(xl)

for i in range(len(nl)):
    for j in range(len(xl)):
        e='(('+nl[i][0]+xl[j][0]+nl[i][1]+')'+xl[j][1]+nl[i][2]+')'+xl[j][2]+nl[i][3]
        f='('+nl[i][0]+xl[j][0]+nl[i][1]+')'+xl[j][1]+'('+nl[i][2]+xl[j][2]+nl[i][3]+')'
        ans=min(ans,eval(e),eval(f))
print ans


import sys
a = map(int, sys.stdin.readline().split(' '))
o = sys.stdin.readline().strip().split(' ')
ad = [False]*4
od = [False]*3
B  = []
OP = []

def calc2(a,b,o):
    if o=='+':
        return a+b
    else:
        return a*b

def calc1():
    r1 = calc2(B[0],calc2(B[1],calc2(B[2],B[3],OP[2]),OP[1]),OP[0])
    r2 = calc2(calc2(B[0],calc2(B[1],B[2],OP[1]),OP[0]),B[3],OP[2])
    r3 = calc2(calc2(calc2(B[0],B[1],OP[0]),B[2],OP[1]),B[3],OP[2])
    r4 = calc2(B[0],calc2(calc2(B[1],B[2],OP[1]),B[3],OP[2]),OP[0])
    r5 = calc2(calc2(B[0],B[1],OP[0]),calc2(B[2],B[3],OP[2]),OP[1])
    #print B
    #print OP
    #print r1,r2,r3,r4,r5
    r = [r1,r2,r3,r4,r5]
    res = 10**13
    for c in r:
        res = min(res,c)
    return res

def solve(i1, i2):
    global B, OP
    res = 10**13
    if i1==4 and i2==3:
        return calc1()
    for i  in range(4):
        if not ad[i]:
            ad[i] = True
            B.append(a[i])
            if i2==3:
                res = min(res, solve(i1+1,i2))
            else:
                for j in range(3):
                    if not od[j]:
                        od[j] = True
                        OP.append(o[j])
                        res = min(res, solve(i1+1,i2+1))
                        OP.pop()
                        od[j] = False
            ad[i] = False
            B.pop()
    return res

print solve(0,0)


def check(a, b, c, d):
    if a > d and b > c:
        return 1
    return 0
a = [0 for i in range(4)]
b = [0 for i in range(4)]
for i in range(4):
    a[i], b[i] = map(int, input().split())
if check(a[0], b[1], a[2], b[3]) and check(a[0], b[1], a[3], b[2]):
    print('Team 1')
elif check(a[1], b[0], a[2], b[3]) and check(a[1], b[0], a[3], b[2]):
    print('Team 1')
elif (check(a[2], b[3], a[0], b[1]) or check(a[3], b[2], a[0], b[1])) and (check(a[3], b[2], a[1], b[0]) or check(a[2], b[3], a[1], b[0])):
    print('Team 2')
else:
    print('Draw')


import sys
import math
from collections import defaultdict

def main():
  p1 = sys.stdin.readline().split()
  p1d = int(p1[0])
  p1a = int(p1[1])
  p2 = sys.stdin.readline().split()
  p2d = int(p2[0])
  p2a = int(p2[1])
  p3 = sys.stdin.readline().split()
  p3d = int(p3[0])
  p3a = int(p3[1])
  p4 = sys.stdin.readline().split()
  p4d = int(p4[0])
  p4a = int(p4[1])

  choices = [0]*4

  if p1d > p4a and p2a > p3d:
    choices[0] = 1
  elif p1d < p4a and p2a < p3d:
    choices[0] = 2
  if p1d > p3a and p2a > p4d:
    choices[1] = 1
  elif p1d < p3a and p2a < p4d:
    choices[1] = 2
  if p1a > p3d and p2d > p4a:
    choices[2] = 1
  elif p1a < p3d and p2d < p4a:
    choices[2] = 2
  if p1a > p4d and p2d > p3a:
    choices[3] = 1
  elif p1a < p4d and p2d < p3a:
    choices[3] = 2

  if (choices[0] == 1 and choices[1] == 1) or (choices[2] == 1 and choices[3] == 1):
    print 'Team 1'
  elif (choices[0] == 2 or choices[1] == 2) and (choices[2] == 2 or choices[3] == 2):
    print 'Team 2'
  else:
    print 'Draw'

if __name__ == '__main__':
  main()


a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
c = tuple(map(int, input().split()))
d = tuple(map(int, input().split()))

def check(el1, el2):
    if el1[0][0] > el2[1][1] and el1[1][1] > el2[0][0]:
        return 1
    if el2[0][0] > el1[1][1] and el2[1][1] > el1[0][0]:
        return 2
    return 0

def check2(el):
    ans = 5
    cd = [(c, d), (d, c)]
    for el2 in cd:
        if check(el, el2) == 2:
            return 2
        ans = min(ans, check(el, el2))
    return ans

def main():
    ans = 5
    aw = [(a, b), (b, a)]
    for el in aw:
        if check2(el) == 1:
            return print('Team 1')
        ans = min(ans, check2(el))
    if ans == 0:
        print("Draw")
    else:
        print("Team 2")

main()


#include<iostream>
#include<cstdio>
using namespace std;
int a[5], b[5];
int t1, t2;
int f(int t, int d)
{
	if(a[3] > d && b[4] > t)
		return 1;
	if(a[4] > d && b[3] > t)
		return 1;
	if(a[3] < d && b[4] < t && b[3] < t && a[4] < d)
		return -1;
	return 0;
}
int main()
{
	for(int i = 1; i <= 4; i++)
		scanf("%d%d", &a[i], &b[i]);
	t1 = f(a[1], b[2]);
	t2 = f(a[2], b[1]);
	if(t1 == 1 && t2 == 1)
		printf("Team 2\n");
	else if(t1 == -1 || t2 == -1)
		printf("Team 1\n");
	else
		printf("Draw\n");
	return 0;
}


inp=raw_input().split()
for i in range(len(inp)):
    inp[i]=int(inp[i])
p1=[inp[0],inp[1]]
p2=[inp[2],inp[3]]
p3=[inp[4],inp[5]]
p4=[inp[6],inp[7]]
if p1[0]>p2[0]:
    atk1=p1[0]
    defe1=p2[1]
elif p1[0]<p2[0]:
    atk1=p2[0]
    defe1=p1[1]
else:
    atk1=p1[0]
    defe1=max(p1[1],p2[1])

if atk1>max(p3[0],p4[0]) and defe1>max(p3[1],p4[1]):
    print 'Team 1'
elif (p3[0]>atk1 and p4[1]>defe1) or (p4[0]>atk1 and p3[1]>defe1):
    print 'Team 2'
else:
    print 'Draw'


def gcd(a,b):
    # a作为除数 必须大于b
    a, b = (a, b) if a >=b else (b, a)
    while b:
        a,b = b,a%b
    return a

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

import math
a, b = [int(i) for i in input().split(' ')]
if a % b == 0 or b % a == 0:
    print(0)
else:
    n = abs(a-b)
    ks = []
    for i in range(1, min(n, int(math.sqrt(10**9+1)))):
        if n % i == 0:
            if a % i == 0:
                ks.append(0)
            else:
                ks.append(i - a%i)
            ks.append(n//i - a%(n//i))
    ks = sorted(set(ks))
    k = ks[0]
    # print(ks)
    minn = lcm(a+k, b+k)

    for i in ks[1:]:
        if lcm(a+i, b+i) < minn:
            k = i
            minn = lcm(a+i, b+i)
    print(k)


from fractions import gcd
import math

lcm = lambda a, b: a//gcd(a,b)*b
a, b = (map(int, input().split()))

d = abs(b-a)
divs = {d}
for i in range(2, int(math.sqrt(d))):
    if not d%i: divs |= {i, d//i}

sol = [(lcm(a, b), 0)]
for d in divs:
    k = d-a%d if a%d else 0
    sol.append((lcm(a+k, b+k), k))

print(min(sol)[1])


from math import gcd

def factors(k):
	for i in range(1, int(k ** 0.5)):
		if k % i == 0:
			j = k // i
			yield i
			if i != j: yield j

x, y = map(int, input().split())
d = y - x

ml = float("inf")
mo = 0

for q in factors(d):
	o = (q - (x % q)) % q
	lcm = (x + o) * (y + o) // gcd(x + o, y + o)
	if lcm < ml:
		ml = lcm
		mo = o

print(mo)


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

"""Codeforces Round #554 (Div. 2)

Problem C. Neko does Maths

:author:         Kitchen Tong
:mail:    kctong529@gmail.com

Please feel free to contact me if you have any question
regarding the implementation below.
"""

__version__ = '1.0'
__date__ = '2019-04-24'

import sys

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

def prime_sieve(size):
    sieve = [0, 0] + [1] * (size - 1)
    primes = []
    for i in range(2, size+1):
        if sieve[i] == 1:
            for j in range(i**2, size+1, i):
                sieve[j] = 0
            primes.append(i)
    return (sieve, primes)

def memoize(func):
    memo = {}

    def wrapper(*args):
        n, p, s = args
        if n not in memo:
            memo[n] = func(n, p, s)
        return memo[n]
    return wrapper

@memoize
def rec_fact(n, primes, sieve):
    if sieve[n] == 1:
        return [n]
    if n == 1:
        return []
    for p in primes:
        if n % p == 0:
            return [p] + rec_fact(n//p, primes, sieve)
    return -1

def factorize(n, primes, sieve):
    if sieve[n] == 1:
        return [n]
    p_factors = rec_fact(n, primes, sieve)
    p_dict = dict()
    for p in p_factors:
        if p not in p_dict:
            p_dict[p] = 1
        else:
            p_dict[p] += 1
    factors = [1]
    for p, k in p_dict.items():
        for f in list(factors):
            for exp in range(1, k+1):
                factors += [f * (p ** exp)]
    return sorted(factors)

def solve(a, b):
    a, b = min(a, b), max(a, b)
    if b % a == 0:
        return 0
    diff = b - a
    sieve, primes = prime_sieve(diff)
    factors = factorize(diff, primes, sieve)
    k, lcm = 0, a * b
    for f in factors:
        step = a % f
        if step > 0:
            step = f - step
        this_lcm = (a + step) * (b + step) // gcd(a+step, b+step)
        if this_lcm < lcm:
            lcm = this_lcm
            k = step
    return k

def main(argv=None):
    a, b = map(int, input().split())
    print(solve(a, b))
    return 0

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


import math
a,b = map(int,input().split())
def lcm(a,b):
    if(a>b):
        min1=a
    else:
        min1=b
    while(1):
        if(min1%a==0 and min1%b==0):
            return(min1)
        min1=min1+1
min1 =lcm(a,b)
k=0
num = abs(a-b)
if num >=10**4 :
    num = 10**4
    for i in range(1,num):
    min2 =lcm(a+i,b+i)
    if min2<min1:
    min1 = min2
    k = i
    print(k)
elif num == 1:
    print(0)
else:
    for i in range(1,num):
        min2 =lcm(a+i,b+i)
        if min2<min1:
            min1 = min2
            k = i
    print(k)


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int val(char c) {
   if (c >= '0' and c <= '9') {
      return int(c) - int('0');
   } else if (c >= 'A' and c <= 'Z') {
      return int(c) - int('A') + 10;
   }
}

int sum(const vector<int>& x, int radix) {
   int S = 0, r = 1;
   for (int i = 0; i < x.size(); i++) {
      S += x[i] * r;
      r *= radix;
   }
   return S;
}

int main() {
   char c;
   vector<int> a, b, *x = &a;
   int max = 0;
   while (cin >> c) {
      int v = val(c);
      if (c == ':') {
         x = &b;
      } else {
         x->push_back(v);
         if (v > max) max = v;
      }
   }
   reverse(a.begin(), a.end());
   reverse(b.begin(), b.end());
   if (a[0] >= 24) {
      cout << 0 << endl;
   } else if (a[0] == sum(a, 1) and b[0] == sum(b, 1)) {
      cout << -1 << endl;
   } else {
      int i = max + 1;
      while (sum(a, i) < 24 and sum(b, i) < 60) {
         cout << i++ << ' ';
      }
      if (i == max + 1) {
         cout << 0 << endl;
      } else {
         cout << endl;
      }
   }
}


#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <climits>
#include <algorithm>
#include <iterator>
#include <functional>
#include <limits>
#include <numeric>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <list>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <stdexcept>
#include <utility>
#include <cassert>
#include <complex>
using namespace std;
#define LEFT(i) ((i) << 1)
#define RIGHT(i) (((i) << 1) | 1)
#define MID(i) ((l[i] + r[i]) >> 1)
#define CC(i, v) memset(i, v, sizeof(i))
#define REP(i, l, n) for(int i = l;i < int(n);++i)
#define FOREACH(con, i) for(__typeof(con.begin()) i = con.begin();i != con.end();++i)
template<class T>bool checkmax(T &a,T b){return a < b ? a = b, 1 : 0;}
template<class T>bool checkmin(T &a,T b){return a > b ? a = b, 1 : 0;}
typedef long long LL;
typedef pair<int, int> PII;
template<class T> void string_reader(string s, vector<T>& vec){
	istringstream sin(s);
	copy(istream_iterator<T>(sin), istream_iterator<T>(), back_inserter(vec));
}
const int LEN = 1010;
void prefix(const char *mode, int *next)
{
	int m = strlen(mode), k = -1, i;
	next[0] = -1;
	for (i = 1; i < m; i++)
	{
		while (k > -1 && mode[k + 1] != mode[i]) k = next[k];
		if (mode[k + 1] == mode[i]) k++;
		next[i] = k;
	}
}
int prev[LEN], next[LEN];
const int N = 100010;
int max_prev[N], max_next[N];
string str, sub;
int main()
{
	ios::sync_with_stdio(false);
	int m, n, maxn, q, ans;
	while(cin >> str)
	{
		cin >> m;
		n = str.size(), ans = 0;
		REP(k, 0, m)
		{
			cin >> sub;
			if(sub.size() == 1)
			{
				ans += find(str.begin(), str.end(), sub[0]) != str.end();
				continue;
			}
			prefix(sub.c_str(), prev);
			maxn = q = -1;
			REP(i, 0, n)
			{
				while(q > -1 && sub[q + 1] != str[i]) q = prev[q];
				if(str[i] == sub[q + 1]) ++q;
				maxn = max(maxn, q);
				max_prev[i] = maxn;
			}
			reverse(sub.begin(), sub.end());
			maxn = q = -1;
			prefix(sub.c_str(), next);
			for(int i = n - 1;i >= 0;i--)
			{
				while(q > -1 && sub[q + 1] != str[i]) q = next[q];
				if(str[i] == sub[q + 1]) ++q;
				maxn = max(maxn, q);
				max_next[i] = maxn;
			}
			REP(i, 0, n - 1)
			{
				if(max_prev[i] + max_next[i + 1] == sub.size() - 2)
				{
					ans++;
					break;
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std;
struct s
{
    int val,ind;
};
s arr[100003];
bool cmp(s a,s b)
    return a.val<b.val;
}
int main()
{
    int n,i;
    bool works;
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        scanf("%d",&arr[i].val);
        arr[i].ind=i;
    }
    sort(arr+1,arr+n+1,cmp);
    printf("%d\n",n/2+n%2);
    works=0;
    for (i=1;i<=n;i+=2)
    {
        if (!works) works=1;
        else printf(" ");
        printf("%d",arr[i].ind);
    }
    printf("\n");
    printf("%d\n",n/2);
    works=0;
    for (i=2;i<=n;i+=2)
    {
        if (!works) works=1;
        else printf(" ");
        printf("%d",arr[i].ind);
    }
    printf("\n");
    return 0;
}


#!/bin/python

time = raw_input()
h, m = time.split(':')
h = h.lstrip('0')
m = m.lstrip('0')

#print h,m
if h=='' and m=='':
	print -1
#hallelujah
elif len(h)==1 and len(m)==1:
	if( 'A'<=h[0] and h[0]<='Z' and (ord(h[0])-ord('A')+10) > 24:
		print 0
	else:
		print -1

else:
	ans = []
	for base in xrange(1,61):
		#print "base :", base
		invalid = 0

		temp = 1
		dec_h = 0
		for i in reversed(h):
			if '0' <= i and i <= '9':
				if ord(i)-ord('0') >= base:
					invalid = 1
			#		print "hour_digit", base
					break
				dec_h += temp*(ord(i) - ord('0'))

			else:
				if ord(i)-ord('A')+10 >= base:
					invalid=1
			#		print "hour_alpha"
					break
				dec_h += temp*(ord(i) - ord('A') + 10)

			temp *= base

		if dec_h > 23:
			invalid = 1

		if invalid == 1:
			continue

		temp = 1
		dec_m = 0
		for i in reversed(m):
			if '0'<= i and i <= '9':
				if ord(i)-ord('0') >= base:
		#			print "min_digit"
					invalid = 1
					break
				dec_m += temp*( ord(i) - ord('0') )
			else:
				if ord(i)-ord('A')+10 >= base:
					invalid = 1
		#			print "min_alpha"
					break
				dec_m += temp*(ord(i) - ord('A') + 10)

			temp *= base

		if dec_m > 59:
			invalid = 1

		if invalid == 1:
			continue

		ans.append(base)

	le = len(ans)

	if le == 0:
		print le
	else:
		for i in xrange(le-1):
			print ans[i],
		print ans[le-1]


import sys

def val(c):
    if c >= '0' and c <= '9':
        return ord(c) - ord('0')
    return ord(c) - ord('A') + 10

def ok(s, base, limit):
    sum = 0
    cur = 1
    t = s[::-1]
    for c in t:
        v = val(c)
        if v >= base:
            return False
        sum = sum + cur * v
        cur = cur * base
    return sum < limit

t = sys.stdin.readline()
t = t.rstrip()
ind = t.find(':')
h = t[0:ind]
m = t[ind+1:]

#print h,m

if ok(h, 100, 24) and ok(m, 100, 60):
    print -1
    exit()

ans = []
base = 2
while base <= 36:
    if ok(h, base, 24) and ok(m, base, 60):
        ans.append(base)
    base = base + 1
if len(ans) == 0:
    print 0
    exit()
print ans.pop(0),
for val in ans:
    print val,
print


    from itertools import *
    n, k = map(int, raw_input().split())
    a = [raw_input() for _ in range(n)]
    idx = list(permutations(range(k), k))
    res = 99999999
    for j in idx:
        b = [int(''.join(x[i] for i in j)) for x in a]
        diff = max(b) - min(b)
        if diff < res: res = diff
    print res


def f(x, t):
    d = int(x) * (10 ** (len(t[0]) - 1))
    p = [(d, d)]
    for i in t:
        u, v = [y for y in i if y >= x], [y for y in i if y < x]
        d = []
        if u:
            u = min(u)
            u = [u] + sorted(list(i - {u}))
            u = int(''.join(u))
            d.extend((a, max(b, u)) for a, b in p)
        if v:
            v = max(v)
            v = [v] + sorted(list(i - {v}), reverse = True)
            v = int(''.join(v))
            d.extend((min(a, v), b) for a, b in p)
        p = d
    return min(b - a for a, b in p)

n, k = map(int, input().split())
t = [set(input()) for i in range(n)]
p = {i for i in '0123456789' if all(i in j for j in t)}
s = [z - p for z in t]
ans = min(f(x, t) for x in '0123456789')
for x in p:
    y = p - {x}
    s = [z - y for z in t]
    ans = min(min(f(x, t) for x in '0123456789'), ans)
print(ans)


for i in range(n):
    a.append(input())

s = 1000000000000
for i in range(fact(k)):
    b = []

    for j in range(n):
        x = list(permutations(a[j]))[i]
        x = ''.join(x)
        x = int(x)
        b.append(x)

    mx = max(b)
    mn = min(b)

    if mx - mn < s:
        s = mx - mn

print(s)


import numpy as np
import itertools as it

n, k = [int(i) for i in input().split()]
a = np.array([list(input()) for i in range(n)]).astype(int)
p = np.arange(k)
b = 10 ** p[::-1]
print(min([np.max(np.sum(a[:, i] * b, axis=1)) - np.min(np.sum(a[:, i] * b, axis=1))
           for i in it.permutations(p)]))


import sys

data = sys.stdin.read().split()
data_ptr = 0

def data_next():
    global data_ptr, data
    data_ptr += 1
    return data[data_ptr - 1]

N = int(data_next())
K = int(data_next())

arr = []
for i in range(N):
    arr.append(list(data_next()));

perm = []
for i in range(K):
    perm.append(str(i))

def next_perm():
    global perm, arr
    for i in reversed(range(len(perm) - 1)):
        if perm[i] < perm[i + 1]:
            break
        elif i == 0:
            return False
    for j in reversed(range(i + 1, len(perm))):
        if perm[i] < perm[j]:
            break
    perm[i], perm[j] = perm[j], perm[i]
    perm[i + 1:] = reversed(perm[i + 1:])
    for k in range(len(arr)):
        arr[k][i], arr[k][j] = arr[k][j], arr[k][i]
        arr[k][i + 1:] = reversed(arr[k][i + 1:])
    return True

ans = 1000000000
while True:
    ans = min(ans, int("".join(max(arr))) - int("".join(min(arr))))
    if (not(next_perm())):
        break

print(ans)


#!/usr/bin/python3

def solve(n):
  if n == 0:
    return (0, 0)
  n -= 1

  x = 1
  y = 2
  c = 6
  k = 1
  while n >= c:
    x += 2
    n -= c
    c += 6
    k += 1

  lim = [k - 1] + [k] * 5
  dx = [-1, -2, -1, 1, 2, 1]
  dy = [2, 0, -2, -2, 0, 2]

  i = 0
  while n > 0:
    t = min(n, lim[i])
    x += t * dx[i]
    y += t * dy[i]
    n -= t
    i += 1

  return (x, y)

x, y = solve(int(input()))
print(x, y)
# for i in range(21):
#   print(i, solve(i))


n = raw_input()
n = int(n)
k = 6
loops = 0

while n >= k:
    n -= k
    k += 6
    loops += 1

pos = [loops * 2, 0]

if n == 0:
    print pos[0], pos[1]
else:
    moves = [(1, 2), (-1, 2), (-2, 0), (-1, -2), (1, -2), (2, 0), (1, 2)]
    factors = [loops + 1 for i in range(1, 8)]
    factors[0] = 1
    factors[1] -= 1

    j = 0
    while n > 0:
        if factors[j % 7] == 0:
            j += 1
            continue
        for k in range (factors[j % 7]):
            pos[0] += moves[j % 7][0]
            pos[1] += moves[j % 7][1]
            n -= 1
            if (n == 0):
                break

        j += 1

    print pos[0], pos[1]


st = input()

l = [(-2,0),(-1,-2), (1,-2),(2,0),(1,2),(-1,2)]
a = 6

n = 1
ru = 0
yy = 0
while (ru <= st):
	ru += n*a
	n += 1
	yy += 1
ru -= (n-1)*a
yy -= 1
#print ru , yy
diff = st - ru

if (st <= 6):
	if (st == 0):
		print "0 0"
		exit()

	if (st == 1):
		print "1 2"
		exit()
	if (st == 2):
		print "-1 2"
		exit()
	if (st == 3):
		print "-2 0"
		exit()
	if (st == 4):
		print "-1 -2"
		exit()
	if (st == 5):
		print "1 -2"
		exit()
	if (st == 6):
		print "2 0"
		exit()

x = 2*(yy)
y = 0

if (diff == 0):
	print x , y
	exit()
elif (diff == 1):
	x += 1
	y += 2
	print x, y
	exit()
elif (diff <= yy+1):
	x += 1
	y += 2
	diff -= 1
	x -= 1*diff
	y += 2*diff
	print x , y
	exit()

elif (diff > yy+1):
	x += 1
	y += 2
	x -= yy
	y += 2*yy
	diff -= yy+1
	li = 0

	while (diff > yy+1 ) :
		if (li < len(l)):
			x += l[li][0]*(yy+1)
			y += l[li][1]*(yy+1)
			diff -= (yy+1)
			li += 1
		else:
			break

	x += l[li][0]*diff
	y += l[li][1]*diff
	print x,y
	exit()


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

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

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

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

fields = [(2 * (c + 1), 0)]
for dx, dy in [(-1, 2), (-2, 0), (-1, -2), (1, -2), (2, 0), (1, 2)]:
    for i in range(c + 1):
        x, y = fields[-1]
        fields.append((x + dx, y + dy))
print(*fields[n + 1])


#!/usr/bin/env python

import sys
import logging
import traceback

logging.basicConfig(level = logging.INFO)

ROD_NUM = 3
matrix = [map(int, raw_input().split()) \
            for i in range(ROD_NUM)]
n = input()

dp = [[[0 for k in range(ROD_NUM)] \
        for j in range(ROD_NUM)] \
        for i in range(n+1)]

for i in range(1, n+1) :
    for j in range(ROD_NUM) :
        for k in range(ROD_NUM) :
            if j == k :
                pass
            else :
                def getBridge(x, y) :
                    for b in range(ROD_NUM) :
                        if b not in [x, y] :
                            return b
                    return -1

                b = getBridge(j, k)
                # print i, j, k, b
                dp[i][j][k] = min(dp[i-1][j][b] + matrix[j][k] + dp[i-1][b][k],
                                dp[i-1][j][k] + matrix[j][b] + dp[i-1][k][j] + matrix[b][k] + dp[i-1][j][k])

print dp[n][0][2]


t = []
for i in range(3):
  t.append(map(int, raw_input().split()))
n=input()
c = []
for m in range(n+1):
    row = [ [0]*3 for i in range(3) ]
    c.append(row)

for m in range(1,n+1):
    for i in range(3):
        for j in range(3):
            if i!=j:
                k = 3-i-j
                a = c[m-1][i][k] + t[i][j] + c[m-1][k][j]
                b = c[m-1][i][j] + t[i][k] + c[m-1][j][i] + \
                    t[k][j] + c[m-1][i][j]
                c[m][i][j] = min(a,b)
print c[n][0][2]


def play(price, n):
    # dp[i][j][k] -  naimen'shaya stoimost' peremeshcheniya i blinov so sterzhnya j => k
    # U nas vsegda est' dva varianta dejstviya:
    # 1. Peremeshchaem i - 1 blin na mesto 2. Dalee, peremeshchaem i - yj blin na mesto 3. I nakonec peremeshchaem i - 1 blin na mesto 3.
    # 2. Peremeshchaem i - 1 blin na mesto 3. Zatem i - yj na mesto 2, zatem i - 1 blin na mesto 1, dalee i -yj na 3-e mesto i nakonec i - 1 blin na 3 mesto
    # t.e, dp[i][j][k] = min(dp[i - 1][j][k ^ j] + Price[j][k] + dp[i - 1][k ^ j][k],
    # dp[i - 1][j][k] + Price[j][k ^ j] + dp[i - 1][k][j] + Price[j ^ k][k] + dp[i - 1][j][k])

    dp = [[[0 for k in range(0, 4)] for j in range(0, 4)] for i in range(0, n + 1)]

    for i in range(1, n + 1):
        for j in range(1, 4):
            for k in range(1, 4):
                dp[i][j][k] = min(dp[i - 1][j][k ^ j] + price[j][k] + dp[i - 1][k ^ j][k], 2 * dp[i - 1][j][k] + price[j][k ^ j] + dp[i - 1][k][j] + price[j ^ k][k])

    return dp[n][1][3]

def main():
    matrix = [[0 for j in range(0, 4)] for i in range(0, 4)]
    i = 1
    while i < 4:
        row = list(map(int, input().split()))
        for j in range(1, 4):
            matrix[i][j] = row[j - 1]
        i += 1

    n = int(input())

    print(play(matrix, n))

main()
#print(play([[0, 0, 0, 0], [0, 0, 1, 1],[0, 1, 0, 1],[0, 1, 1, 0]], 3))


def play(price, n):
    # dp[i][j][k] -  наименьшая стоимость перемещения i блинов со стержня j => k
    # У нас всегда есть два варианта действия:
    # 1. Перемещаем i - 1 блин на место 2. Далее, перемещаем i - ый блин на место 3. И наконец перемещаем i - 1 блин на место 3.
    # 2. Перемещаем i - 1 блин на место 3. Затем i - ый на место 2, затем i - 1 блин на место 1, далее i -ый на 3-е место и наконец i - 1 блин на 3 место
    # т.е, dp[i][j][k] = min(dp[i - 1][j][k ^ j] + Price[j][k] + dp[i - 1][k ^ j][k],
    # dp[i - 1][j][k] + Price[j][k ^ j] + dp[i - 1][k][j] + Price[j ^ k][k] + dp[i - 1][j][k])

    dp = [[[0 for k in range(0, 4)] for j in range(0, 4)] for i in range(0, n + 1)]

    for i in range(1, n + 1):
        for j in range(1, 4):
            for k in range(1, 4):
                dp[i][j][k] = min(dp[i - 1][j][k ^ j] + price[j][k] + dp[i - 1][k ^ j][k], 2 * dp[i - 1][j][k] + price[j][k ^ j] + dp[i - 1][k][j] + price[j ^ k][k])

    return dp[n][1][3]

def main():
    matrix = [[0 for j in range(0, 4)] for i in range(0, 4)]
    i = 1
    while i < 4:
        row = list(map(int, input().split()))
        for j in range(1, 4):
            matrix[i][j] = row[j - 1]
        i += 1

    n = int(input())

    print(play(matrix, n))

main()
#print(play([[0, 0, 0, 0], [0, 0, 1, 1],[0, 1, 0, 1],[0, 1, 1, 0]], 3))


import fileinput
i=0
costMatrix = []

for line in fileinput.input():
    if i<3:
        costMatrix.append([int(i) for i in line.split()])
        i+=1
    else:
        n = int(line)

def switchC(MAT):
    SW = [[0]*3 for i in range(3)]
    SW[0][1]=MAT[0][2]
    SW[0][2]=MAT[0][1]
    SW[1][0]=MAT[1][0]
    SW[2][0]=MAT[1][0]
    SW[1][2] = MAT[2][1]
    SW[2][1] = MAT[1][2]
    return SW

def switchC2(MAT):
    SW = [[0]*3 for i in range(3)]
    SW[0][1]=MAT[1][0]
    SW[0][2]=MAT[1][2]
    SW[1][0]=MAT[0][1]
    SW[2][0]=MAT[2][1]
    SW[1][2] = MAT[0][2]
    SW[2][1] = MAT[2][0]
    return SW

def switchC3(MAT):
    SW = [[0]*3 for i in range(3)]
    SW[0][1]=MAT[2][1]
    SW[0][2]=MAT[2][0]
    SW[1][0]=MAT[1][2]
    SW[2][0]=MAT[0][2]
    SW[1][2] = MAT[1][0]
    SW[2][1] = MAT[0][1]
    return SW

def hashMAT(n,MAT):
    M = max(n,MAT[0][1],MAT[0][2],MAT[1][0],MAT[1][2],MAT[2][0],MAT[2][1])
    hashed = n + M*MAT[0][1]+M**2*MAT[0][2]+M**3*MAT[1][0]+M**4*MAT[1][2]+M**5*MAT[2][0]+M**6*MAT[2][1]
    return hashed

a = {}

def SmallY(n,MAT):
    h = hashMAT(n,MAT)
    isIN = h in list(a.keys())
    if n == 1:
        if isIN:
            return a[h]
        else:
            a[h] = min(MAT[0][2], MAT[0][1]+MAT[1][2])
            return a[h]
    else:
        if isIN:
            return a[h]
        else:
            a[h] = min(MAT[0][2]+SmallY(n-1,switchC(MAT))+SmallY(n-1,switchC2(MAT)),MAT[0][1]+MAT[1][2]+2*SmallY(n-1,MAT)+SmallY(n-1,switchC3(MAT)))
            return a[h]

print(SmallY(n,costMatrix))


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

import sys
import math
import random
import operator
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
getcontext().prec = 100

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

n = int(raw_input())
rmax = 0
intervals = []
for _ in xrange(n):
    l, r = map(int, raw_input().split())
    rmax = max(rmax, r)
    intervals.append((l, r))

def prob_smaller_equal(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(val + 1 - l, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_smaller(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(val - l, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_greater(ints, val):
    res = 1.0
    for l, r in ints:
        d = min(r - val, r + 1 - l)
        if d <= 0:
            return 0.0
        res *= float(d) / (r + 1 - l)
        if res == 0.0:
            return 0.0
    return res

def prob_equal(ints, val):
    res = 1.0
    for l, r in ints:
        if not (l <= val <= r):
            return 0.0
        res *= 1.0 / (r + 1 - l)
    return res

def combos(ints, minn, maxn):
    for ntie in xrange(minn, maxn + 1):
        for ints_tie in combinations(ints, r=ntie):
            yield ints_tie

INTINDS = range(len(intervals))
res = 0
for i_int1 in INTINDS:
    for i_ints2_tie in combos(INTINDS, 1, n - 1):
        if i_int1 in i_ints2_tie:
            continue
        i_other = [i for i in INTINDS if i not in i_ints2_tie and i != i_int1]

        int1 = intervals[i_int1]
        ints2_tie = [intervals[i] for i in i_ints2_tie]
        other = [intervals[i] for i in i_other]

        for price in xrange(1, rmax + 1):
            add = prob_smaller(other, price) * prob_equal(ints2_tie, price) * prob_greater([int1], price)
            # if add:
                # print int1, " | ", ints2_tie, " : ", "price2", price, "*", add, "=", add * price
            res += add * price

# print

for i_ints1_tie in combos(INTINDS, 2, n):
    i_other = [i for i in INTINDS if i not in i_ints1_tie]

    ints1_tie = [intervals[i] for i in i_ints1_tie]
    other = [intervals[i] for i in i_other]
    for price in xrange(1, rmax + 1):
        add = prob_smaller(other, price) * prob_equal(ints1_tie, price)
        # if add:
            # print ints1_tie, " | ", other, " : ", "price2", price, "*", add, "=", add * price
        res += add * price

print res


def recul(s, dex, cntBig, cntSame) :
    global n, L
    if cntBig > 1 : return 0.0
    if dex == n :
        if cntBig > 1 : return 0.0
        elif cntBig == 1 :
            if cntSame == 0 : return 0.0
            else : return 1.0
        else :
            if cntSame < 2 : return 0.0
            else : return 1.0

    ret = 0.0
    P = [0,0,0]
    total = L[dex][1]-L[dex][0]+1
    P[0] = min(max((s - L[dex][0]) / total, 0.0), 1.0)
    P[1] = 0 if s < L[dex][0] or s > L[dex][1] else 1.0/total
    P[2] = min(max((L[dex][1] - s) / total, 0.0), 1.0)
    ret += recul(s, dex+1, cntBig+1, cntSame) * P[2]
    ret += recul(s, dex+1, cntBig, cntSame+1) * P[1]
    ret += recul(s, dex+1, cntBig, cntSame) * P[0]
    return ret

n = int(input())
L = []
for i in range(n) :
    l,r = map(int, input().split(' '))
    L.append([l,r])
ans = 0.0
S = [0]*10001
for s in range(1, 10001) :
    S[s] = recul(s, 0, 0, 0)
for s in range(1, 10001) :
    ans += s*S[s]
print('{0:.10f}'.format(ans))


import sys

MaxV = int(1e4)

data = []
readIdx = 0
for line in sys.stdin.readlines():
	data += line.split()

def read():
	global readIdx
	readIdx += 1
	return data[readIdx - 1]

n, average, power, mul = int(read()), 0, 1, 1
froms, tos, r = [], [], []

def check(secondMax, mask):
	global n
	equal, greater, ways = 0, 0, 1
	greaterFrom, greaterTo = secondMax + 1, MaxV
	for i in range(n):
		which = int(mask) % 3
		mask /= 3
		if which == 0:
			ways *= max(0, min(secondMax - 1, tos[i]) + 1 - froms[i])
		elif which == 1:
			equal += 1
			ways *= (froms[i] <= secondMax and tos[i] >= secondMax)
		else:
			greater += 1
			greaterFrom = max(greaterFrom, froms[i])
			greaterTo = min(greaterTo, tos[i])
	if greater > 0:
		ways *= max(0, greaterTo + 1 - greaterFrom)
	if ways > 0 and ((greater == 1 and equal > 0) or (greater == 0 and equal >= 2)):
		return ways * secondMax
	return 0

for i in range(n):
	froms += [int(read())]
	tos += [int(read())]
	power *= 3
	mul *= (tos[i] + 1 - froms[i])
for secondMax in range(MaxV + 1):
	for mask in range(power):
		x = check(secondMax, mask)
		if x:
			r += [x]
print(sum(r) / mul)


import sys

MaxV = int(1e4)

data = []
readIdx = 0
for line in sys.stdin.readlines():
	data += line.split()

def read():
	global readIdx
	readIdx += 1
	return data[readIdx - 1]

n, r, power, mul = int(read()), 0, 1, 1
froms, tos = [], []

def check(secondMax, mask):
	global n
	equal, greater, ways = 0, 0, 1
	greaterFrom, greaterTo = secondMax + 1, MaxV
	for i in range(n):
		which = int(mask) % 3
		mask /= 3
		if which == 0:
			ways *= max(0, min(secondMax - 1, tos[i]) + 1 - froms[i])
		elif which == 1:
			equal += 1
			ways *= (froms[i] <= secondMax and tos[i] >= secondMax)
		else:
			greater += 1
			greaterFrom = max(greaterFrom, froms[i])
			greaterTo = min(greaterTo, tos[i])
	if greater > 0:
		ways *= max(0, greaterTo + 1 - greaterFrom)
	if ways > 0 and ((greater == 1 and equal > 0) or (greater == 0 and equal >= 2)):
		return ways * secondMax
	return 0

for i in range(n):
	froms += [int(read())]
	tos += [int(read())]
	power *= 3
	mul *= (tos[i] + 1 - froms[i])
for secondMax in range(MaxV + 1):
	for mask in range(power):
		r += check(secondMax, mask)
print(r / mul)


C, H1, H2, W1, W2 = map(int, raw_input().split())

if H1 * W2 < H2 * W1:
    H1, H2 = H2, H1
    W1, W2 = W2, W1

r = C % W1
x0 = C // W1
best = 0
for k in xrange(min(x0 + 1, W2)):
    ans_opt = (x0 - k) * H1 + (r + k * W1) * H2 / W2
    if ans_opt < best:
        break
    ans = (x0 - k) * H1 + (r + k * W1) // W2 * H2
    best = max(ans, best)
print best


C, Ha, Hb, Wa, Wb = (int(x) for x in raw_input().split())

if Ha * Wb > Hb * Wa:
    Ha, Hb, Wa, Wb = Hb, Ha, Wb, Wa

res = 0
for x in xrange(0, Wb):
    r = x * Ha + (C - x * Wa) / Wb * Hb
    res = max(r, res)

print res


C, Hr, Hb, Wr, Wb = map(int, input().split())
ans = 0
for i in range(6 * 10 ** 5):
    if Wr * i <= C:
        ans = max(ans, Hr * i + (C - Wr * i) // Wb * Hb)
for i in range(6 * 10 ** 5):
    if Wb * i <= C:
        ans = max(ans, Hb * i + (C - Wb * i) // Wr * Hr)
print(ans)


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

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

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

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

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

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

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

c, h1, h2, w1, w2 = read_ints()

# stage 2
if w1 < w2:  # most weighted
    (h1, w1), (h2, w2) = (h2, w2), (h1, w1)

mx_h = -1
n1 = 0
while w1 * n1 <= c:
    n2 = (c - w1 * n1) / w2
    if n2 >= 0 and n1 * w1 + n2 * w2 <= c:
        add_h = h1 * n1 + h2 * n2
        # print "mxh", n1, n2, ":", add_h
        mx_h = max(mx_h, add_h)
    n1 += 1
print mx_h


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

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

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


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

def group_of_study ():
    nr_students = raw_input()
    nr_stu_at_score = raw_input().split(' ')
    min_student, max_student = raw_input.split(' ')

    cur = 0
    for cnt, num in enumerate(nr_stu_at_score):
        cur += num
        nr_students -= num
        if (cur >= min_student) and (nr_students <= max_student):
            print cur + 1
            exit
    print '0'

if __name__ == '__main__':
    group_of_study()


m = int(raw_input())
c = map(int, raw_input().split())
d = map(int, raw_input().split())
x, y = d[0], d[1]
g1 = 0
g2 = 0
i=0
k=1
while g1<x:
     g1 += c[i]
     c[i]=-1
     i += 1
     k += 1
i=m-1
while g2<x:
     if c[i] == -1:
         print 0
         exit(0)
     g2 += c[i]
     c[i]=-1
     i -= 1

c = filter(lambda x:x!=-1, c)

if len(c) == 0:
   print k
   exit(0)
else:
  i = 0
  try:
    while g1+c[i]<=y and i<len(c):
      g1 += c[i]
      c[i] = -1
      i += 1
      k += 1
  except: pass
  c = filter(lambda x:x!=-1, c)

  if len(c)==0:
    print k
  elif g2+sum(c) <= y:
    print k
  else: print 0


__author__ = 'MatFuck'

import sys

#sys.stdin = open("1.txt")

m = input()

a = [int(x) for x in raw_input().split()]

[x_c, y_c] = [int(x) for x in raw_input().split() ]

x = 0
x_i = -1
y = 0
y_i = m

while (x < x_c) and (x_i < m):
    x_i += 1
    x += a[x_i]

if x_i == m:
    print 0
    sys.exit(0)

while y < x_c and y_i > x_i:
    y_i -= 1
    y += a[y_i]

if y_i <= x_i:
    print 0
    sys.exit(0)

while x_i + 1 < y_i:
    if (x < y):
        x_i += 1
        x += a[x_i]
    else:
        y_i -= 1
        y += a[y_i]

if (x_c <= x) and (x <= y_c) and (x_c <= y) and (y <= y_c):
    print x_i + 2
else:
    print 0


m = int(input())
c = map(int, input().split())
x, y = [int(i) for i in input().split()]

cumFreq = [0]
total = 0
strong = 0
LSum, RSum = 0, 0
r = range(x, y+1)
for i in c:
    total += i
    cumFreq.append(total)

if max(x, y) * 2 < total:
    print(0)
else:
    k = m//2
    LSum = cumFreq[k]
    RSum = total - LSum
    if LSum in r and RSum in r:
        print(k+1)
    else:
        print(LSum, RSum)
        if LSum > RSum:
            while not (LSum in r and RSum in r):
                k -= 1
                LSum = cumFreq[k]
                RSum = total - LSum
        elif LSum < RSum:
            while not (LSum in r and RSum in r):
                k += 1
                LSum = cumFreq[k]
                RSum = total - LSum
        if LSum in r and RSum in r:
            print(k+1)
        else:
            print(-1)


  n = int(input())
  c = map(int,input().split())
  x,y = map(int,input().split())
  sumc = 0

  for i in range(n):
    sumc += c[i]
    if x <= sumc and sumc<=y and x<=sum(c)-sumc and sum(c)-sumc <= y:
      print(i+2)
      return
  print(0)


import sys
a, b, w, x, c = map(int, input().split())
if c <= a:
    print(0)
    sys.exit()
d = c - a
ans = 0
if b // x >= d:
    print(d)
    sys.exit()
ans += (b // x + 1)
d -= (b // x)
b = w - (x - b % x)
b0 = b
g = 0
det = 0
while (1):
    if b // x >= d:
        print(ans + d)
        sys.exit()
    g += (b // x + 1)
    det += (b // x)
    ans += (b // x + 1)
    d -= (b // x)
    b = w - (x - b % x)
    if b == b0:
        break

ans += (d // det) * g
d %= det
if d == 0:
    print(ans - 1)
    sys.exit()
while (1):
    if b // x >= d:
        print(ans + d)
        sys.exit()
    ans += (b // x + 1)
    d -= (b // x)
    b = w - (x - b % x)


import sys

#sys.stdin = open("input.txt")

a, b, w, x, c = [long(x) for x in raw_input().split()]

t = c - a
hash = {}

if t <= 0:
    print 0
else:
    cur_t = 0

    while 0 < t:
        #print cur_t
        if b >= x:
            if x <= 0:
                print t
                sys.exit()
            else:

                cur_t += b/x
                t -= b/x
                b -= (b/x)*x
        else:
            if (w-x) <= 0:
                print cur_t + (t-cur_t)/2
                sys.exit()
            else:
                delt = max((x-b)/(w-x),1)
                b += (w-x)*delt
                #t += delt
                cur_t += delt
        if t >0:
            if b in hash:
                del_t = t - hash[b][1]
                del_step = cur_t - hash[b][0]
                times = t / -del_t
                cur_t += del_step*times
                t += del_t * times
            else:
                hash[b] = [cur_t, t]

    print cur_t + t


import sys

#sys.stdin = open("input.txt")

a, b, w, x, c = [long(x) for x in raw_input().split()]

t = c - a
hash = {}
jump = 0

if t <= 0:
    print 0
else:
    cur_t = 0

    while 0 < t:
        #print cur_t
        #print b, cur_t, t

        if b >= x:
            if x <= 0:
                print t
                sys.exit()
            else:

                cur_t += b/x
                t -= b/x
                b -= (b/x)*x
        else:
            if (w-x) <= 0:
                print cur_t + (t-cur_t)/2
                sys.exit()
            else:
                delt = max((x-b)/(w-x),1)
                b += (w-x)*delt
                #t += delt
                cur_t += delt
        if t >0 and not jump:
            if b in hash:
                jump = 1
                del_t = t - hash[b][1]
                del_step = cur_t - hash[b][0]
                times = t / -del_t
                cur_t += del_step*times
                t += del_t * times
            else:
                hash[b] = [cur_t, t]

    print cur_t + t


a,b,w,x,c=map(int,raw_input().split())
total=0
while c>a:
   # print b,c,a,total
    if b>=x:
        n=(b/x)
        if n> (c-a):
            n= (c-a)
        c-=n
        b-=n*x
        total+=n
    else:
        c-=1
        a-=1
        b=w-(x-b)
        total+=1
print total


import fileinput;

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

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

print(count+(c-a))


from fractions import gcd

def get_divisors(n):
    divs = []
    i = 1
    while i <= n / i:
        if n % i == 0:
            divs.append(i)
            if n / i != i:
                divs.append(n / i)
        i += 1
    return divs

def f(x, y):
    divs = get_divisors(x)
    dd = {}
    for d in divs:
        mul = y/d*d
        if not mul:
            continue
        if mul not in dd or dd[mul] < d:
            dd[mul] = d
    dd = sorted(dd.items(), reverse=True)
    dd.append((0, 0))
    # for k, w in dd:
    #    print k, w
    ans = 0
    ix = 0
    while y and ix < len(dd):
        y, g = dd[ix]
        # print y, g, ix
        next_y, next_ix = None, None
        for i in xrange(ix+1, len(dd)):
            # print i, dd[i], dd[i][1] % g
            if dd[i][1] % g == 0:
                next_y = dd[i][0]
                next_ix = i
                break
        ans += (y-next_y) / g
        ix = next_ix
        y -= (y-next_y) / g * g
    return ans

def brute(x, y):
    ans = 0
    while y:
        ans += 1
        # print 'x=%d, y=%d->%d, gcd=%d, ans=%d' % (x, y, y-gcd(x, y),
        #                                          gcd(x, y), ans)
        y = y - gcd(x, y)
    return ans
    # if not y:
    #     return 0
    # return 1+brute(x, y-gcd(x, y))

a, b = map(int, raw_input().split())
print f(a, b)
# print brute(2*2*3*5, 2*3*3+1)
# print brute(2*3*3, 2*2*3*5)
# print brute(2*3, 59)
# print brute(59, 6)

# assert brute(6, 3) == 1
# assert brute(3, 5) == 3
# for i in xrange(1, 100):
#     for j in xrange(1, 100):
#        assert brute(i, j) == f(i, j)
# assert f(10**9+9, 10**9+8) == 10**9+8


from sys import stdin, stdout
from math import factorial
from math import log10

INF = float('inf')

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

def f(a, b, u):
    if not b:
        return 0

    if not fact:
        return b // u

    mx = -INF

    for v in fact:
        if b - (b % (u * v)) > mx:
            mx =  max(mx, b - (b % (u * v)))
            cur = v

    while not mx and fact:
        fact.pop()

    if mx:
        fact.pop(fact.index(cur))
        return (b - mx) // u + f(a, mx, u * cur)
    else:
        return f(a, b, u)

a, b = map(int, stdin.readline().split())
fact = []

q = gcd(a, b)

i = 2
k = a // q

while i * i <= a:
    while not k % i:
        fact.append(i)
        k //= i

    i += 1

if k != 1:
    fact.append(k)

stdout.write(str(f(a, b, q)))


def readline():
    return map(int, raw_input().split())

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

def is_prime(p):
    for i in range(2, p):
        if i * i > p: break
        if p % i == 0: return False

    return True

def divisors(n):
    p = 2
    while n > 1 and p * p <= n:
        if n % p == 0: yield p
        while n % p == 0: n /= p
        p += 1
    if n > 1: yield n

def main():
    a, b = readline()
    g = gcd(a, b)
    a /= g
    b /= g

    answer = 0

    while b > 0:
        arr = map(lambda p: b // p * p, divisors(a))
        if len(arr) != 0:
            new_b = max(arr)
        else:
            new_b = 0

        answer += b - new_b

        b = new_b
        g = gcd(a, b)
        a /= g
        b /= g

    print answer

if __name__ == '__main__':
    main()


a,b=map(int,input().split())
A=[]
for i in range(2,int(a**0.5)+1):
    while a%i==0:
        a//=i
        A.append(i)
if a!=1:
    A.append(a)

#print(A)
out=0
while b>0:
    n=len(A)
    x=-1
    for i in range(n):
        if x==-1 or b%A[i]<b%A[x]:
            x=i

    if n==0:
        out+=b
        b=0
        break

    A[x],A[n-1]=A[n-1],A[x]
    out+=b%A[n-1]
    b//=A.pop()
print(out)


def binary_gcd(a,b):
    d=0
    while a%2==0 and b%2==0:
        a=a//2
        b=b//2
        d+=1
    while a!=b:
        if a%2==0:
            a=a//2
        elif b%2==0:
            b=b//2
        else:
            if a>b:
                a=(a-b)//2
            else:
                b=(b-a)//2
    g=a
    return g*2**d
def check_aval(n):
    f=0
    for i in range(2,int(n**0.5+1)):
        if n%i==0:
            f=i
            break
    return f
a,b=map(int,input().split())
i=0
if check_aval(a)==0 or b==1:
    if(b%a!=0  or a==1 or b==1):
        if a>b:
            i=b
        else:
            i=b%a+b//a
        b=0
##    elif b>a:
##        i=b%a+b//a
##        b=0
gcd=1
ar=[]
while  b!=0 and :
    try:
        if gcd==1:
            gcd=binary_gcd(a,b)
        else:
            gcd=gcd*binary_gcd(a//gcd,(b-gcd)//gcd)
        b-=gcd
        i+=1
        if b!=0:
            if check_aval((b-gcd)//gcd)==0:
                i+=b//gcd
                #b=0
                ar.append(i)
                i-=b//gcd
    except:
        i-=1
        gcd=binary_gcd(a,b)
        b-=gcd
        i+=1
##        b-=gcd
##        i+=1
##    else:
##        b-=gcd
##        i+=1
#print(i)
print(min(ar))


def add(a,b):
    if a+b>=mod:
        return (a+b)%mod
    return a+b
n=int(input())*2
s=input()
d=[[0,0] for i in range(len(s)+1)]
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d[i][1]=i+1
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] ==s[0:len(x)-j]:
                d[i][0]=len(x[j::])
                break
    else:
        d[i][0]=i+1
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d[i][1]=len(x[j::])
                break
    aux+=s[i]
d[len(s)][1]=len(s)
d[len(s)][0]=len(s)
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[k][0]]=add(dp[i][j][k],dp[i+1][j-1][d[k][0]])
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[k][1]]=add(dp[i][j][k],dp[i+1][j+1][d[k][1]])
print(dp[n][0][len(s)]%mod)


def add(a,b):
    if a+b>=mod:
        return (a+b)%mod
    return a+b
n=int(input())*2
s=input()
d=dict()
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d.update({(i,1):i+1})
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] ==s[0:len(x)-j]:
                d.update({(len(aux),0):len(x[j::])})
                break
    else:
        d.update({(i,0):i+1})
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d.update({(len(aux),1):len(x[j::])})
                break
    aux+=s[i]
d.update({(len(s),1):len(s)})
d.update({(len(s),0):len(s)})
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[(k,0)]]=add(dp[i][j][k],dp[i+1][j-1][d[(k,0)]])
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[(k,1)]]=add(dp[i][j][k],dp[i+1][j+1][d[(k,1)]])
print(dp[n][0][len(s)]%mod)


n=int(input())*2
s=input()
d=dict()
aux=''
st=set()
st.add(aux)
for i in range(len(s)):
    if s[i]=='(':
        d.update({(i,1):i+1})
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] in st:
                d.update({(len(aux),0):len(x[j::])})
                break
    else:
        d.update({(i,0):i+1})
        x=aux+'('
        for j in range(1,i+2):
            if x[j::] in st:
                d.update({(len(aux),1):len(x[j::])})
                break
    aux+=s[i]
    st.add(aux)
d.update({(len(s),1):len(s)})
d.update({(len(s),0):len(s)})
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[(k,0)]]=(dp[i][j][k]+dp[i+1][j-1][d[(k,0)]])%mod
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[(k,1)]]=(dp[i][j][k]+dp[i+1][j+1][d[(k,1)]])%mod
print(dp[n][0][len(s)]%mod)


n=int(input())*2
s=input()
d=dict()
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d.update({(i,1):i+1})
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] ==s[0:len(x)-j]:
                d.update({(len(aux),0):len(x[j::])})
                break
    else:
        d.update({(i,0):i+1})
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d.update({(len(aux),1):len(x[j::])})
                break
    aux+=s[i]
d.update({(len(s),1):len(s)})
d.update({(len(s),0):len(s)})
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[(k,0)]]=(dp[i][j][k]+dp[i+1][j-1][d[(k,0)]])%mod
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[(k,1)]]=(dp[i][j][k]+dp[i+1][j+1][d[(k,1)]])%mod
print(dp[n][0][len(s)]%mod)


n=int(input())*2
s=input()
d=dict()
aux=''
st=set()
st.add(aux)
for i in range(len(s)):
    if s[i]=='(':
        d.update({(i,1):i+1})
        x=aux+')'
        for j in range(1,i+2):
            if x[j::] in st:
                d.update({(len(aux),0):len(x[j::])})
                break
    else:
        d.update({(i,0):i+1})
        x=aux+'('
        for j in range(1,i+2):
            if x[j::] in st:
                d.update({(len(aux),1):len(x[j::])})
                break
    aux+=s[i]
    st.add(aux)
d.update({(len(s),1):len(s)})
d.update({(len(s),0):len(s)})
dp=[[[0 for i in range(n+1)] for j in range(n+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,n):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[(k,0)]]=(dp[i][j][k]+dp[i+1][j-1][d[(k,0)]])%mod
    for j in range(n-1):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[(k,1)]]=(dp[i][j][k]+dp[i+1][j+1][d[(k,1)]])%mod
print(dp[n][0][len(s)]%mod)


'''''''''''
   Author : code_marshal
'''''''''''

alp = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
k, s = int(input()), list(input())
ch = alp[:k]
j=len(s)//2
i=len(s)//2-1
while i>=0 or j<len(s):
    if s[i]=='?':
        if s[~i]!='?': s[i]=s[~i]
        else:
            lol = list(set(ch)-set(s)); lol.sort(reverse=True)            k = 0
            for l in lol:k=l; break
            if k==0: s[i]=s[~i]=ch[0]
            else: s[i]=s[~i]=k
            if '?' not in s: break
    if s[j]=='?':
        if s[~j]!='?': s[j]=s[~j]
        else:
            lol = list(set(ch)-set(s)); lol.sort(reverse=True)
            k = 0
            for l in lol:k=l; break
            if k==0: s[j]=s[~j]=ch[0]
            else: s[j]=s[~j]=k
            if '?' not in s: break
    i-=1;j+=1

if s[::-1]==s and not set(ch)-set(s): print(''.join(s))
else: print("IMPOSSIBLE")


import sys
n = input()
s = list(raw_input())
abc = sorted(set(('zyxwvutsrqponmlkjihgfedcba')[26-n:]) - set(s))
sl = len(s)/2

for i in xrange(sl):
    j = -i-1
    if s[i] == '?' and s[j] != '?': s[i] = s[j]
    elif s[j] == '?' and s[i] != '?': s[j] = s[i]
    elif s[i] != s[j]:
        print 'IMPOSSIBLE'
        sys.exit()

sl += 1 if sl == 1
for i in xrange(sl-1,-1,-1):
    if s[i] == '?':
        s[i] = s[-i-1] = abc.pop() if abc else 'a'

print ''.join(s) if not abc else 'IMPOSSIBLE'


import sys
n = input()
s = list(raw_input())
abc = sorted(set(('zyxwvutsrqponmlkjihgfedcba')[26-n:]) - set(s))
sl = len(s)/2

for i in xrange(sl):
    j = -i-1
    if s[i] == '?' and s[j] != '?': s[i] = s[j]
    elif s[j] == '?' and s[i] != '?': s[j] = s[i]
    elif s[i] != s[j]:
        print 'IMPOSSIBLE'
        sys.exit()

s += 1 if sl == 1
for i in xrange(sl-1,-1,-1):
    if s[i] == '?':
        s[i] = s[-i-1] = abc.pop() if abc else 'a'

print ''.join(s) if not abc else 'IMPOSSIBLE'


Z='IMPOSSIBLE'
I=input
k=int(I())
s=list(I())
p=s[::-1]
for i in range(len(s)):
	if s[i]==p[i]:continue
	if s[i]=='?':s[i]=p[i]
	elif p[i]=='?':p[i]=s[i]
	else:print(Z);exit()
d=set(chr(i)for i in range(97,97+k)if chr(i) not in s)
for i in range(len(s)//2+len(s)%2,-1,-1):
	if len(d) and s[i]=='?':s[i]=s[len(s)-i-1]=max(d);d.remove(max(d))
s=''.join(s).replace('?','a')
print([Z,s][set(s)==set(chr(i)for i in range(97,97+k))])


import math, time, re, UserString

rInt = lambda s: int(s)
rFloat = lambda s: float(s)
rLong = lambda s: long(s)
rLine = lambda f: f.readline()

def main():
    def body():
        k = rInt(raw_input())
        s = raw_input()
        s = UserString.MutableString(s)
        n = len(s)
        l = [chr(97 + i) for i in xrange(0, k)]
        b = [False for i in xrange(0, k)]
        tt = 0
        for i in xrange(0, (n + 1) / 2):
            if (((s[i] == '?') and (s[n - i - 1] != '?'))):
                s[i] = s[n - i - 1]
                b[ord(str(s[i])) - 97] = True
            elif (((s[i] != '?') and (s[n - i - 1] == '?'))):
                s[n - i - 1] = s[i]
                b[ord(str(s[i])) - 97] = True
            elif((s[i] == '?') and (s[n - i - 1] == '?')):
                tt += 1
            else:
                b[ord(str(s[i])) - 97] = True

        t = len([a for a in b if (not a)])
        #print t, tt
        f1 = True
        f2 = True
        for i in xrange(0, (n+1)/2):
            if (s[i] not in l and s[i] != '?'):
                f1 = False
            elif (s[i] != s[n - i - 1]):
                f2 = False
        #print b
        #print t, tt, f1, f2
        if (t <= tt and f1 and f2):
            j = 0
            d = tt - t
            while (d > 0):
                if(s[j] == '?'):
                    s[j] = 'a'
                    s[n - j - 1] = 'a'
                    b[0] = True
                    d -= 1
                j += 1
            for i in xrange(0, (n + 1)/2):
                if (s[i] == '?'):
                    j = 0
                    while(b[j] == True):
                        j += 1
                    s[i] = l[j]
                    s[n - i - 1] = l[j]
                    b[j] = True
            print s
        else:
            print 'IMPOSSIBLE'

        #print s
        #print l

        return

    try:
        name = ''
        f1 = open(name + '.in', 'r')
        f2 = open(name + '.out', 'w')
        print >> f2, body()
        f1.close()
        f2.close()
    except IOError:
        body()
    except:
        print 'Sudden error!'
        raise

start = time.time()
main()
#print 'Time exceeded:', time.time() - start


def main():
	x = int(input())
	ans = 0
	for i in range(2, x):
		ans += i*(i+1)
	print ans

if __name__ == '__main__':
	main()


n=int(input()
su =0
for i in range(2,n-1)
    su=su+(i)*(i+1
print(su)


//f = open('Text.txt',"r")
n = int(f.read())
res = 0

for x in range(3, n+1):
    res += 1*(x-1)*(x)

print(res)


Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate untitled-1.py]
1?AA
100


d = {"?": 10, "A":10, "B":10,"C": 10,"D":10,"E":10, "F":10,"G": 10,"H":10,"I":10, "J":10}

lett = set(list("ABCDEFGHIJ"))

for i in range(10):
    d[str(i)]=1

print d

k = set(d.keys())

total = 1

#with open("task1.txt", "r") as f:
#    for line in f:
for line in sys.stdin:
    if line[0] == "?":
        total *= 9
    elif line[0] >= "A" and line[0] <= "J":
        total *= 9
        d[line[0]] = 1
        lett.remove(line[0])
        for m in lett:
            d[m] -= 1

    for c in line[1:]:
        if c not in k:
            break
        total *= d[c]
        if c in lett:
            d[c] = 1
            lett.remove(c)
            for m in lett:
                d[m] -= 1
    break

print total


s = raw_input()

k = 1
buk = []
bu = ['A','B','C','D','E','F','G','H','I','J']

if s[0] in bu:
    k = k*9
    buk = s[0]
elif s[0] == '?':
    k = k*9

for i in range(len(s)):
    if s[i] in bu and buk == []:
        k = k*10
        buk.append(b[i])
    elif s[i] in bu and buk != [] and s[i] not in buk:
        k = k*(10-len(buk))
    elif s[i] == '?':
        k = k*10
print k


s = raw_input()

sum = 1
mulA=10

usedChars = {
'A' : False,
'B' : False,
'C' : False,
'D' : False,
'E' : False,
'F' : False,
'G' : False,
'H' : False,
'I' : False,
'J' : False,
}

if s[0] >= 'A' and s[0] <= 'Z':
    usedChars[ s[0] ] = True
    mulA -= 1
    sum *= 9

if s[0] == '?':
    sum *= 9

for ch in s[1:]:
    if ch == '?':
        sum *= 10
    elif not usedChars[ ch ]:
        sum *= mulA
        mulA -= 1
        usedChars[ch] = True

print sum


def check(temp,a):
    dr = {}
    nums = '0123456789'
    a = list(str(a));
    for i in range(len(temp)):
        if temp[i] == '?':
            if a[i] in nums:
                continue
            else:
                return 0
        if temp[i] in nums:
            if temp[i] == a[i]:
                continue
            else:
                return 0
        if temp[i] != '?':
            if temp[i] not in nums:
                if temp[i] not in dr.keys() and a[i] not in dr.values():
                    dr[temp[i]] = a[i]
    for i in range(len(temp)):
        if temp[i] != '?' and temp[i] not in nums and a[i]:

            if temp[i] not in dr.keys() or a[i] != dr[temp[i]]:
                return 0
    return 1

n = input()
leng = len(n)
ans = 0
for i in range(10**(leng-1),10**leng):
    if check(n,i) == 1:
        ans += 1
print(ans)


# This code is contributed by Siddharth

from sys import *
input = stdin.readline

import random
from bisect import *
import math
from collections import *
import operator
from heapq import *
from itertools import *
inf=10**18
mod=10**9+7

# inverse modulo power pow(a,-1,mod) - it only works on py 3.8 ( *not in pypy )

# ==========================================> Code Starts Here <=====================================================================

def solve(x):
    if dp[x]!=-1:
        return dp[x]
    if x<=1:
        dp[x]=0
        return 0
    if x==2:
        dp[x]=2
        return 2
    ans=0
    for i in range(1,x):
        ans=(ans+max(1,solve(x-i)))%m
    for i in range(2,x+1):
        if i>x:
            continue
        ans=(ans+max(1,solve(x//i)))%m
    dp[x]=ans%m
    return dp[x]

n,m=map(int,input().split())
dp=[-1]*(n+5)
print(solve(n)%m)


import sys
input = sys.stdin.readline

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

S=[i for i in range(n+1)]

for i in range(2,n+1):
    if S[i]==i:
        for j in range(i,n+1,i):
            if S[j]==j:
                S[j]=i

def fact(x):
    NOW={1}
    while x!=1:
        NOW|={n*S[x] for n in NOW}
        x//=S[x]

    return NOW

DP=[0]*(n+1)

DP[1]=1
DP[2]=2
DP[3]=5
#DP[4]=12
#DP[5]=25

for i in range(4,n+1):
    SU=DP[i-1]*2+1

    for f in fact(i):
        if f==1 or f==i:
            continue
        SU+=DP[i//f]-DP[(i-1)//f]

    DP[i]=SU%m

print(DP[n])


for u in range(int(input())):
    n, m = map(int, input().split())
    dp = [0 for i in range(n+1)]
    dp[1] = 1
    p = [0]*(n+1)
    cache = [[] for i in range(n+1)]

    a = 0
    b = 1

    for i in range(2, n+1):
        for j in cache[i]:
            a = (a - dp[p[j]] + m)%m
            p[j] += 1
            a = (a + dp[p[j]])%m

        a = (a + dp[1])%m
        dp[i] = (a + b)%m
        b = (b + dp[i])%m

        p[i] = 1
        j = 2
        while(i*j <= n):
            cache[i*j].append(i)
            j += 1

    print(dp[n])


import sys
import io, os
import math
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
def ceil(a,b):
    a=-a
    k=a//b
    k=-k
    return k
# arr=list(map(int, input().split()))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def strinp(testcases):
    k = 5
    if (testcases == -1 or testcases == 1):
        k = 1
    f = str(input())
    f = f[2:len(f) - k]
    return f
def main():
    arr=list(map(int, input().split()))
    n=arr[0]
    m=arr[1]
    dp=[0]*(n+1)
    dp[1]=1
    dp[2]=2
    dp[3]=5
    if(n<4):
        print(dp[n])
        sys.exit()
    for i in range(4,n+1):
        dp[i]=(2*dp[i-1]+1)%m
        p=int(i**(0.5))
        for j in range(2,p+1):
            if(i%j==0):
                if(j*j==i):
                    dp[i]+=(dp[i//j]-dp[(i-1)//j])
                    dp[i]=dp[i]%m
                else:
                    f=i//j
                    dp[i]+=(dp[i//j]-dp[(i-1)//j])
                    dp[i] += (dp[i // f] - dp[(i - 1) // f])
                    dp[i]=dp[i]%m
    print(dp[n])
main()


from sys import stdin
from math import sqrt
# raw_input = input
# xrange = range
raw_input = lambda: stdin.readline().rstrip()
input = lambda: int(raw_input())
I=lambda: map(int, raw_input().split())
n,m = I()
dp = [0]*(n+1)
dp[1] = 1
s = 1
for x in xrange(2, n+1):
	w = 0
	q = int(sqrt(x))
	q1 = q+(0 if q**2==x else 1)
	q2 = q1-1
	for j in xrange(2, q1): #j<sqrt(x)
		w = (w+dp[x//j])%m
	for c in xrange(1, q+1):
		a1 = x//(c+1)
		a2 = x//c
		w = (w+(dp[c]*(a2-a1)%m)%m
	dp[x] = (s + w)%m
	s = (s+dp[x])%m
print(dp[n])


def pall(n):
    if str(n)==str(n)[::-1]:
        return True
    else:
        return False
def sieve(n):
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
n=10**5
prime = [True for i in range(n+1)]
nopr=[0]*(n+1)
pallin=[0]*(n+1)
sieve(n)
prime[1]=False
for i in range(2,n+1):
    if prime[i]:
        nopr[i]=nopr[i-1]+1
    else:
        nopr[i]=nopr[i-1]
for i in range(1,n):
    if pall(i):
        pallin[i]=pallin[i-1]+1
    else:
        pallin[i]=pallin[i-1]
p,q = map(int,input().split())
#print(pallin[:100],nopr[:100])
for i in range(n,0,-1):
#    print(nopr[i],pallin[i],nopr[i]*q,pallin[i]*p)
    if q*(nopr[i])<=p*(pallin[i]):
        print(i)
        exit()
print("Palindromic tree is better than splay tree")


# #------------------------template--------------------------#
# import os
import sys
# from math import *
# from collections import *
# from fractions import *
# from bisect import *
# from heapq import*
# from io import BytesIO, IOBase
def vsInput():
     sys.stdin = open('input.txt', 'r')
     sys.stdout = open('output.txt', 'w')
# 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")
# ALPHA='abcdefghijklmnopqrstuvwxyz'
# M=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

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

def isPalindrome(n):
    n=str(n)
    return n==n[::-1]

N=10**7
primes=primeN(N)

palindrome=[0,1]
prime=[0,0]

for i in range(2,N+1):
    if(isPalindrome(i)):
        palindrome.append(palindrome[-1]+1)
    else:
        palindrome.append(palindrome[-1])

    if(primes[i]):
        prime.append(prime[-1]+1)
    else:
        prime.append(prime[-1])

# print(prime[40])
# print(palindrome[40])

ans="Palindromic tree is better than splay tree"
p,q=value()

for i in range(1,N+1):
    if( prime[i]*q <= p*palindrome[i]):
        ans=i

print(ans)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

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

def isPalindrome(n):
    n=str(n)
    return n==n[::-1]

N=10**7
primes=primeN(N)

palindrome=[0,1]
prime=[0,0]

for i in range(2,N+1):
    if(isPalindrome(i)):
        palindrome.append(palindrome[-1]+1)
    else:
        palindrome.append(palindrome[-1])

    if(primes[i]):
        prime.append(prime[-1]+1)
    else:
        prime.append(prime[-1])

# print(prime[40])
# print(palindrome[40])

ans="Palindromic tree is better than splay tree"
p,q=value()

for i in range(1,N+1):
    if( prime[i]*q <= p*palindrome[i]):
        ans=i

print(ans)


import sys
import math

p, q = map(int, sys.stdin.readline().split())

def is_palindrome(x):
    s = str(x)
    return all([s[i] == s[len(s)-1-i] for i in xrange(len(s)/2)])

def get_primes(x):
    arr = [0, 1] + [1, 0]*(x/2)
    for i in xrange(2, int(math.ceil(math.sqrt(n)))+1, 2):
        for j in xrange(i+2, x):
            if j % (i+1) == 0:
                arr[j-1] = 0
    res = [0]*x
    for i in xrange(1, x):
        res[i] = res[i-1] + arr[i]
    return res

n = 2
rub = [1]
while(1):
    if is_palindrome(n):
        rub.append(rub[-1]+1)
    else:
        rub.append(rub[-1])
    if n >= 17 and p*rub[-1] < q * n / math.log(n):
        break
    n += 1

pi = get_primes(n)

while(q*pi[n-1] > p*rub[n-1]):
    n -= 1

print >> sys.stdout, n


# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

MX = 3 * 10 ** 6
prime = [1] * MX
prime[0] = prime[1] = 0
for i in xrange(2, int(MX ** 0.5 + 1e-8)):
    if prime[i]:
        prime[2 * i::i] = [0] * len(prime[2 * i::i])

p, q = map(int, raw_input().split())
pi = rub = ans = 0
for i in xrange(1, MX):
    pi += prime[i]
    if i == int(str(i)[::-1]): rub += 1
    if q * pi <= p * rub:
        ans = max(ans, i)

print ans


from collections import*
n,m=map(int,input().split())
c=Counter(i*i%m for i in range(1,n+1))
print(sum(c[k]*c[(m-k)%m]for k in c))


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

from collections import defaultdict
from math import factorial as f
from fractions import gcd as g

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

def brute ():
    p = []
    for i in range (1, n + 1):
        for j in range (1, n + 1):
            if (i * i + j * j) % m == 0:
                p.append ((i, j))
    return p

ret = 0
if m == 1:
    print n * n
else:
    print len (brute ())


n,m=map(int,input().split())
a=[0]*m
for i in range(1,m+1):a[i*i%m]+=(n-i)//m+1
print(sum(zip(a,(a+a)[n::-1])))


n,m=list(map(int,input().split()))
a=[[0 for i in range(m)] for i in range(m)]
s=0
for i in range(m):
    for j in range(m):
        a[i][j]=(i+1)**2+(j+1)**2
        if a[i][j]%m==0:
            a[i][j]=1
        else:
            a[i][j]=0
        s=s+a[i][j]
s=s*((n//m)**2)
b=n%m
for i in range(b):
    s=s+sum(a[i][:n])
for i in range(b):
    for j in range(n):
        s=s+a[i][j]
for i in range(b):
    for j in range(b):
        s=s+a[i][j]
print(s)


import io , sys , atexit , os

def freopen(filename, mode):
    if mode == "r":
        sys.stdin = open(filename, mode)

    elif mode == "w":
        sys.stdout = open(filename, mode)

# ---- MAIN ----

freopen("input.txt", "r")
#freopen("output.txt", "w")

c = 0
n,m = map(int,raw_input().split())

for i in range(1,m+1):
	for j in range(1,m+1):
		num = i*i + j*j
		num = num%m
		if(num==0):
			c += (1+(n-i)/m) * (1+(n-j)/m)

print c


def next_permutation(a):
    k = len(a) - 2
    while a[k] > a[k+1]:
        k -= 1
    t = k + 1
    while t < len(a) - 1 and a[t+1] > a[k]:
        t += 1
    a[t], a[k] = a[k], a[t]
    sub = a[k+1:]
    sub.reverse()
    return a[:k+1] + sub

def count_current(a, x):
    r = 0
    for i in range(len(a) // 2):
        f = a[2*i]
        n = a[2*i + 1]
        r += x[f][n] + x[n][f]
    return r

def count(a, x):
    r, t = 0, a
    while len(t) > 1:
        r += count_current(t, x)
        t = t[1:]
    return r

arr = []
for i in range(5):
    arr.append([int(c) for c in input().split()])
p = [0, 1, 2, 3, 4]
res = 0
while p != [4, 3, 2, 1, 0]:
    res = max(res, count(p, arr))
    p = next_permutation(p)
print(res)


from itertools import permutations

f = lambda i,j: G[i][j]+G[j][i]

G = [[map(int, input().split())] for _ in range(5)]

print(max(f(a,b) + f(b,c) + 2 * (f(c,d)+f(d,e))
          for a,b,c,d,e in permutations(range(5))))


# http://codeforces.com/problemset/problem/431/B

'''
notice that first with second student, and second with the third will
communicate one time, and third with fourth student, and fourth with fifth —
will communicate two times. Another pairs of students will never communicate to
each other during they stay in queue.
'''

from itertools import permuations
q,t = 0, [list(map, int(input().split())) for i in range(5)]

for a,b,c,d,e in permutaions([0,1,2,3,4]):
    s = t[a][b] +t[b][a] +t[b][c] +t[c][b] + 2*(t[c][d] + t[d][c] +t[d][e] + t[e][d])
    if s>q:
        q = s
print(q)


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

# In[204]:

# # n = int(input())
# # line = list(map(int, input().split()))
# # line = list(str(input()))

# In[396]:

# 0 43 21 18 2
# 3 0 21 11 65
# 5 2 0 1 4
# 54 62 12 0 99
# 87 64 81 33 0

# In[413]:

g_mat = []

for _ in range(5):
    g_mat.append(list(map(int, input().split())))

# In[439]:

def utility_function(states, seq):
    score = (states[seq[0]][seq[1]] + states[seq[1]][seq[0]]              + states[seq[2]][seq[3]] + states[seq[3]][seq[2]])             +(states[seq[1]][seq[2]]+ states[seq[2]][seq[1]]              + states[seq[3]][seq[4]] + states[seq[4]][seq[3]])             + (states[seq[2]][seq[3]] + states[seq[3]][seq[2]])             + (states[seq[3]][seq[4]] + states[seq[4]][seq[3]])

    return score

# In[450]:

def permutation(seq):
    def backtrack(first = 0):
        if first == n:
            if seq[:] not in combs:
                combs.append(seq[:])

        else:
            for i in range(first, n):
                seq[first], seq[i] = seq[i], seq[first]
                backtrack(first + 1)
                seq[first], seq[i] = seq[i], seq[first]

    n = len(seq)
    combs = []
    backtrack()
    return combs

# In[455]:

combs = permutation(seq)
max_score = 0

for seq in combs:
    max_score = max(max_score, utility_function(g_mat, seq))

print(max_score)

# In[ ]:


# http://codeforces.com/problemset/problem/431/B

'''
notice that first with second student, and second with the third will
communicate one time, and third with fourth student, and fourth with fifth —
will communicate two times. Another pairs of students will never communicate to
each other during they stay in queue.
'''

from itertools import permutations
q,t = 0, [list(map, int(input().split())) for i in range(5)]

for a,b,c,d,e in permutaions([0,1,2,3,4]):
    s = t[a][b] +t[b][a] +t[b][c] +t[c][b] + 2*(t[c][d] + t[d][c] +t[d][e] + t[e][d])
    if s>q:
        q = s
print(q)


import collections
import sys
def recur(_list):
    idx = -1
    next_list = []
    for i,x in enumerate(_list):
        if x > 1:
            idx = i
            q = _list[idx] // 2
            r = _list[idx] % 2
            next_list += [q,r,q]
        else:
            next_list += [x]
    if idx == -1:
        return _list
    else:
        return recur(next_list)

sys.setrecursionlimit(100000)
n,s,e = list(map(int,input().split(' ')))
_list = [n]
print(collections.Counter(recur(_list[:])[s-1:e])[1])


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

k=0

def get_p2(n):
    i=1
    while n>=i:
        i*=2
    i-=1
    return int(i)

p=get_p2(citire[0])

def get_num(i,n,len):
    key=len//2+1
    if i==key:
        return n%2
    elif i>key:
        i-=key
    n//=2
    len=(len+1)//2-1
    return get_num(i,n,len)

for i in range(citire[1],citire[2]+1):
    n=citire[0]
    len=p
    k+=get_num(i,n,len)

print(k)


# http://codeforces.com/problemset/problem/768/B
import math, copy

def module():
    global li

    i = 0
    while i < len(li):
        if li[i] not in [0, 1]:
            a = math.floor(li[i] / 2)
            b = li[i] % 2

            li.insert(i, a)
            li[i + 1] = b
            li.insert(i + 2, a)

            # print(li)

            i += 3
        else:
            i += 1

    end = 1
    for i in range(len(li)):
        if li[i] not in [0, 1]:
            end = 0
            break
        else:
            continue

    if end == 0:
        module()
    else:
        return

n, l, r = map(int, input().split())
li = [n]
ans = 0

module()
for i in range(l - 1, r):
    ans += li[i]

print(ans)


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

a = [0]
if r == l:
    print 0
    exit()

while n >= 2:
    a.append(n % 2)
    n /= 2
ans = r - l + 1
for i in range(1, len(a)):
    if a[i] == 0:
        d = len(a) - i + 1
        ans -= len([j for j in range(l, r + 1) if j % (2**(d)) == 2**(d-1)])

print ans


n, l,r = map(int, raw_input().split())
if n = 0:
    return 0
if n = 1:
    return 1

a = [0]

while n >= 2:
    a.append(n % 2)
    n /= 2
ans = r - l + 1
for i in range(1, len(a)):
    if a[i] == 0:
        d = len(a) - i + 1
        ans -= len([j for j in range(l, r + 1) if j % (2**(d)) == 2**(d-1)])

print ans


#------------------------------warmup----------------------------
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")

#-------------------game starts now-----------------------------------------------------
x,y=map(int,input().split())
a=y
b=y
c=y
t=1
ans=0
while(True):
    if a==x and b==x and c==x:
        break
    ans+=1
    if t==1:
        a=b+c-1
        if a>x:
            a=x
    elif t==2:
        b=a+c-1
        if b>x:
            b=x
    else:
        c=b+a-1
        if c>x:
            c=x
    t=(t+1)%3
print(ans)(ans,f)
print(ans)


x = int(input())
y = int(input())
x_v = [y, y, y]
result = 0
while ((x_v[0] != x) or (x != x_v[1] ) or  (x != x_v[2])):
    x_v.sort()
    x_v[0] = min(x, x_v[1] + x_v[2] - 1)
    result += 1
print(result)


x = int(input())
y = int(input())
x_v = [y]*3
sum = 0
result = 0
while (x_v[0] != x) or (x != x_v[1] ) or  (x != x_v[2]):
    x_v.sort()
    x_v[0] = min(x, x_v[1] + x_v[2] - 1)
    result += 1
print(result)


# area of equilater triangle s**2 * sqrt(3) / 4
from math import sqrt

answers = {}

def solve(s1, s2, s3, y, ite):
    if s1 == y and s2 == y and s3 == y:
        return ite
    if (s1, s2, s3, y) in answers.keys():
        return answers[(s1, s2, s3, y)]
    big = max(max(s1, s2), s3)
    small = min(min(s1, s2), s3)
    other = s1+s2+s3-big-small
    rest = other-small
    new = max(rest+1, y)
    bigg = max(big-1, y)
    ite_min = 300000
    if new == y and bigg == y:
        return solve(small, other, new, y, ite+1)
    for i in range(new, bigg):
        ite_min = min(ite_min, solve(small, other, i, y, 0))
    answers[(s1, s2, s3, y)] = ite_min + ite + 1
    return ite_min + ite + 1

x, y = [int(i) for i in input().split()]
print(solve(x, x, x, y, 0))


x = int(input())
y = int(input())
x_v = [x]*3
sum = 0
result = 0
while (x_v[0] != y) or (y != x_v[1] ) or (y != x_v[2]):
    temp = x_v[sum%3]
    if sum%3 == 0:
        c = x_v[0]
        a = x_v[1]
        b = x_v[2]
        if (sum == 0) and (y < int(x/3)):
            if (abs(a - b) < int(x/3)) :
                x_v[0] = int(x/3)
            else:
                x_v[0] = abs(a - b) + 1
        else:
            if abs(a - b) < y:
                x_v[0] = y
            else:
                x_v[0] = abs(a - b) + 1
    elif sum%3 == 1:
        c = x_v[1]
        a = x_v[0]
        b = x_v[2]
        if abs(a - b) < y:
            x_v[1] = y
        else:
            x_v[1] = abs(a - b) + 1
    else:
        c = x_v[2]
        a = x_v[0]
        b = x_v[1]
        if abs(a - b) < y:
            x_v[2] = y
        else:
            x_v[2] = abs(a - b) + 1
    if (x_v[sum%3] != temp):
        result += 1
    sum += 1
print(result)


from bisect import*
A=lambda:map(int,input().spilt())
t,=A()
for  _ in [0]*t:
    n,k=A();x=sorted(A());A();a=q=0;m=[n-i-bisect_left(x,x[~i]-k)for i in range(n):
    for i in range(n):a=max(a,q+bisect_right(x,x[i]+k-i);q=max(q,m[~i])
    print(a)


import math

def solve(n,k,s,t):

    #총 세개의 dp state 존재

    #dont change the current character
    #change the current character to t0
    #change the current character to t1

    dp = [[[-1*math.inf for i in range(n+1)] for j in range(n+1)] for z in range(n+1)]
    dp[0][0][0] = 0

    for i in range(n):
        for ck in range(k+1):
            for cnt0 in range(n+1):
                if dp[i][ck][cnt0] == -1*math.inf: continue
                e0 = s[i] == t[0]
                e1 = s[i] == t[1]
                e01 = t[0] == t[1]

                #first transition
                if e1 == 1: e1 = cnt0
                else: e1 = 0
                dp[i+1][ck][cnt0+e0] = max(dp[i+1][ck][cnt0+e0], dp[i][ck][cnt0] + e1)

                if ck < k:
                    #second transition
                    if e01 == 1: e01 = cnt0
                    else: e01 = 0
                    dp[i+1][ck+1][cnt0+1] = max(dp[i+1][ck+1][cnt0+1], dp[i][ck][cnt0] + e01)
                    #third transition
                    dp[i+1][ck+1][cnt0+e01] = max(dp[i+1][ck+1][cnt0+e01], dp[i][ck][cnt0] + cnt0)

    ans = 0

    for ck in range(k+1):
        for cnt0 in range(n+1):
            ans = max(ans, dp[n][ck][cnt0])

    print(ans)

if __name__ == '__main__':
    n,k = map(int,input().split())
    s = input()
    t = input()
    solve(n,k,s,t)


def solve(i, z, k):
    if i >= n:
        return 0
    if dp[i][z][k] != -1:
        return dp[i][z][k]
    o = solve(i+1, z, k)
    c = s[i] != t[0]
    if k >= c:
        o = max(o, solve(i+1, z+1, k-c))
    c = s[i] != t[1]
    if k >= c:
        o = max(o, solve(i+1, z+(t[0] == t[1]), k-c) + z)
    dp[i][z][k] = o
    return o

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

dp = [[[-1] * (n+1) for _ in [0] * n for _ in [0]*n]

print(solve(0, 0, k))


s = raw_input()
ans = -1
for i in range(1,len(s)):
    for j in range(i+1, len(s)):
        a = s[:i]
        b = s[i:j]
        c = s[j:]
        if (a[0]!='0' or int(a)==0) and (b[0]!='0' int(b)==0) and (c[0]!='0' or int(c)==0) and int(a)<=1000000 and int(b)<=1000000 and int(c)<=1000000:
            ans = max([ans, int(a)+int(b)+int(c)])
print ans


res = -1

def perebor(num, a, b):
	global res
	fail = 0

	if b == len(num):
		b = a + 2
		a = a + 1

	if a == len(num) - 1 and b == len(num):
		return

	x = num[0:a]
	y = num[a:b]
	z = num[b:]
	if len(x) > 1:
		if x[0] == '0':
			fail = 1
	if len(y) > 1:
		if y[0] == '0':
			fail = 1
	if len(z) > 1:
		if z[0] == '0':
			fail = 1

	if fail == 0:
		if int(x) <= 1000000 and int(y) <= 1000000 and int(z) <= 1000000:
			t = int(x) + int(y) + int(z)
			if t > res:
				res = t

	b += 1
	perebor(num, a, b)

num = raw_input()
perebor(num, 1, 2)
print res


def f(t, k, s):
    if k == 1:
        if t[0] == '0' and len(t) > 1: return -1
        d = int(t)
        if d > 1000000: return -1
        return s + d
    if t[0] == '0': return f(t[1: ], k - 1, s)
    p = [(t[i: ], int(t[: i])) for i in range(1, len(t) + 2 - k)]
    return max(f(a, k - 1, s + b) for a, b in p if b < 1000001)
print(f(input(), 3, 0))


import sys
import math
import string
from collections import deque

# Function #
def read_int() :
    temp = raw_input().split();
    return map(int, temp);

def read_str() :
    temp = raw_input().split();
    return temp;

def write(output) :
    sys.stdout.write(output);

def writeln(output) :
    sys.stdout.write(str(output)+'\n');
# Class #

INF = 9123456789123456789
# Main Entry #

# Inner Function #
def len_int(now) :
    temp = set();
    while now > 0 :
        temp.add(now%10);
        now /= 10;
    return len(temp);
    pass

ans = 0;
def dfs(now, limit) :
    global ans;
    if now > limit :
        return;
    if now!=0 :
        #print "DEBUG", now;
        ans += 1;
    for ii in xrange(0, 10) :
        if (now*10+ii!=0) and len_int(now*10+ii) <= 2 :

            dfs(now*10+ii, limit);
        pass
    pass

if __name__ == '__main__':

    tc = read_int()[0];
    dfs(0, tc);
    print ans;

    pass
# End Here #


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


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


#!/home/kameda/pyenv2/bin/python

power2list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
'''
If the head of n (:(len(str(n))=i) is fixed as 'x',
number of candidates trailing digit is
9*(2^(i-1)-1)+1
9: len(range(0,10) except x)
(2^(i-1)-1): number of patterns like (xxy xyx xyy) if i=3
1: number of patterns like xxx if i=3

trailing_candidates = []
for i in range(1, 10):
    trailing_candidates.append(9*(2**(i-1)-1)+1)

'''
trailing_candidates = [1, 10, 28, 64, 136, 280, 568, 1144, 2296]
'''
For each head (1..9), trailing_candidates can be applied.
So, cumulative candidates lower than 10^i is calculated as below.

cumulative_candidates = [9]
for i in range(1, 9):
    cumulative_candidates.append(9*trailing_candidates[i]+cumulative_candidates[i-1])

'''
cumulative_candidates = [9, 99, 351, 927, 2151, 4671, 9783, 20079, 40743]

def main_y_fixed(n, y):
    #Count candidates which is n or less starting with n[0] (=x) given y (!=x)
    x = n[0]
    len_n = len(n)
    uln = 0
    if len_n == 1:
        return 1
    if int(y) > int(x):
        if int(n[1]) < int(x): # e.g. 42????? given 8 -> No candidates
            pass
        elif int(n[1]) == int(x): # e.g. 44????? given 8
            uln += main_y_fixed(n[1:], y)
        elif int(n[1]) < int(y): # e.g. 47????? given 8 -> 4488888 is the largest
            uln += power2list[len_n-2]
        elif int(n[1]) == int(y): # e.g. 48????? given 8
            uln += power2list[len_n-2]
            uln += main_y_fixed(n[1:], x)
        elif int(n[1]) > int(y): # e.g. 49????? given 8 -> 4888888 is the largest
            uln += power2list[len_n-1]
    elif int(y) == int(x):
        raise ValueError('2nd argument should be different from 1st degit of 1st argument')
    elif int(y) < int(x):
        if int(n[1]) < int(y): # e.g. 82????? given 4 -> No candidates
            pass
        elif int(n[1]) == int(y): # e.g. 84????? given 4
            uln += main_y_fixed(n[1:], x)
        elif int(n[1]) < int(y): # e.g. 87????? given 4 -> 8488888 is the largest
            uln += power2list[len_n-2]
        elif int(n[1]) == int(x): # e.g. 88????? given 4
            uln += power2list[len_n-2]
            uln += main_y_fixed(n[1:], y)
        elif int(n[1]) > int(y): # e.g. 89????? given 4 -> 8888888 is the largest
            uln += power2list[len_n-1]
    return uln

def main(n):
    #Count candidates which is n or less starting with n[0] (=x)
    x = n[0]
    len_n = len(n)
    uln = 0
    if len_n == 1:
        return 1
    if int(n[1]) > 0:
        for i in range(0, int(n[1])): #int(n[0]), ~int(n[1])-1 and all trailings
            if i != int(n[0]):
                uln += power2list[len_n-2]
            else:
                uln += trailing_candidates[len_n-2]
    if len_n == 2:
        return uln+1
    if int(n[0]) < int(n[1]):
        if int(n[2]) < int(n[0]): #e.g. 482????? -> 47777777 is the largest.
            pass
        elif int(n[2]) == int(n[0]): #e.g. 484?????
            uln += main_y_fixed(n[2:], n[1])
        elif int(n[2]) < int(n[1]): #e.g. 486????? -> 48488888 is the largest.
            uln += power2list[len_n-3]
        elif int(n[2]) == int(n[1]): #e.g. 488?????
            uln += power2list[len_n-3]
            uln += main_y_fixed(n[2:], n[0])
        elif int(n[2]) > int(n[1]): #e.g. 489?????
            uln += power2list[len_n-2]
    elif int(n[0]) == int(n[1]):
        uln += main(n[1:])
    elif int(n[0]) > int(n[1]):
        if int(n[2]) < int(n[1]): #e.g. 842????? -> 83333333 is the largest.
            pass
        elif int(n[2]) == int(n[1]): #e.g. 844?????
            uln += main_y_fixed(n[2:], n[0])
        elif int(n[2]) < int(n[1]): #e.g. 846????? -> 84488888 is the largest.
            uln += power2list[len_n-3]
        elif int(n[2]) == int(n[0]): #e.g. 848?????
            uln += power2list[len_n-3]
            uln += main_y_fixed(n[2:], n[1])
        elif int(n[2]) > int(n[1]): #e.g. 849?????
            uln += power2list[len_n-2]
    return uln

if __name__ == "__main__":
    N = raw_input()
    Len_N = len(N)
    if Len_N <= 2:
        print(N)
        exit(0)
    Uln = cumulative_candidates[Len_N-2] # below 10^len_n
    Uln += (int(N[0])-1)*trailing_candidates[Len_N-1] # between 10^len_n and n[0]*10^len_n
    Uln += main(N)
    print(Uln)
    exit(0)


import sys

buyers, cost_per_apple = [int(i) for i in sys.stdin.readline().rstrip().split(' ')]
buyer_descriptions = [i.rstrip() for i in sys.stdin.readlines()]

total_cost = counter = 0

for buyer in buyer_descriptions:
    if buyer == 'halfplus':
        counter += 1
        total_cost += counter*cost_per_apple
        counter *= 2
    elif buyer == 'half':
        total_cost += counter*cost_per_apple
        counter *= 2

print total_cost / 2


n,p=map(int,raw_input().split())
tot,ans=0,0
for i in range(n):
    if raw_input()=='half':
        ans=ans+tot
        tot=tot*2
    else:
        ans=ans+tot+0.5
        tot=tot*2+1
print format(ans*p,'.0f')


import sys
money = 0
apples = 0
customers = []
num_customers, apple_price = [ int(x) for x in sys.stdin.readline().split(' ')

for i in range(num_customers):
    arg = sys.stdin.readline()
    customers.append(arg)

customers = reversed(customers)
for c in customers:
    if c == 'halfplus':
        money += (apples+0.5)*float(apple_price)
        apples = 2*apples+1
    elif c == 'half':
        money += (apples)*float(apple_price)
        apples = 2*apples

print(money)


n, p = map(int, input().split(' '))
ps = [True if input() == "halfplus" else False for _ in range(n)]

t = 0.5
result = 0.5

for x in reversed(ps):
	result += t
    if x:
        t += 0.5
    t *= 2

print(int(result * p))


n, m = map(int, raw_input().split())
a = [raw_input() for i in xrange(n)][::-1]
r = 0.5

if a[0] == 'halfplus':
    r = 1

for i, v in enumerate(a[1:]):
    if v == 'halfplus':
        r = r * 2 + 0.5
    else:
        r = r * 2

ans = 0
for i, v in enumerate(a):
    if v == 'halfplus':

    else:
        ans *= 1


import math

def combin(n, m):
    if n == m:
        return 1
    if n < m:
        return 0

    a = 1
    for i in range(n, n-m, -1):
        a *= i
    b = 1
    for i in range(1, m+1):
        b *= i

    return a / b

(a, b) = input().split()
n = int(a)
p = float(b) * combin(n,3)

for i in range(0, n+1):
    ans = combin(i, 3) + combin(i, 2) * combin(n-i, 1)
    ans += (combin(i, 1)*combin(n-i, 2)) / 2

    if ans >= p:
        print(i)
        break


from math import *

prec = [0, 0.5, 1, 1]

def prob(known, unknown):
    cnt = 0
    ret = 0
    for i in range(4):
        cur = comb(known, i) * comb(unknown, 3 - i)
        cnt += cur
        ret += cur * prec[i]
    return ret / cnt

inp = input().split()
n = int(inp[0])
p = float(inp[1])

for i in range(n + 1):
    if prob(i, n - i) >= p:
        print(i)
        break


from scipy.special import binom, comb
def D(m,n):
    tmp=0
    for k in range(m+1):
        print('(m,k)=(%d, %d)='%(m,k),binom(m,k))
        print('(n+k, m)=(%d, %d)='%(n+k, m), binom(n+k,m))
        print('product=', binom(m,k)*binom(n+k,m))
        tmp+=binom(m,k)*binom(n+k,m)
    print(tmp)
    return tmp
def t(m,n,k):
    print('(m,k)(n+k,m)=', binom(m,k)*binom(n+k,m))

def prob(n,k):
    p1=binom(k,3)/binom(n,3)
    p2=binom(k,2)*(n-k)/binom(n,3)
    p3=1/2*k*binom(n-k,2)/binom(n,3)
    ptot=p1+p2+p3
    return ptot
np=input()
np=np.split(' ')
n=int(np[0])
p=float(np[1])
left=0
right=n
while(left<right):
    k=(left+right)//2
    if(prob(n,k)<p):
        left=k+1
    else:
        right=k

while(prob(n,k)<p):
    k+=1

print(k)


from collections import deque
def readarray(foo): return [foo(x) for x in raw_input().split()]

stairs = []
to = []
color = []
totalcolors = 0
deg = []
priority = []

def doit():
	usedstairs = set()
	visited = set([0])
	stack = []

	res = []
	layer = [0]

	nextcolor = 1
	hasnextcolor = totalcolors > 1

	stack.append([0, -1, -1, 0])

	while stack:
		(u, source, parent, start) = state = stack[-1]

		nexti = None
		nexts = None
		nextv = None
		for i in xrange(start, len(to[u])):
			s = to[u][i]
			if s == source: continue
			if s in usedstairs: continue
			(v1, v2) = stairs[s]
			v = v1 if v2 == u else v2
			if not hasnextcolor and v in visited: continue
			nexti = i
			nexts = s
			nextv = v
			break

		if nexti is None:
			if parent != -1:
				layer.append(parent)
			stack.pop()
			continue

		if nextv not in visited:
			visited.add(nextv)
			layer.append(nextv)
			state[3] = nexti
			stack.append([nextv, nexts, u, 0])
			continue

		usedstairs.add(nexts)
		nextv = priority[nextcolor]
		nextcolor += 1
		hasnextcolor = totalcolors > nextcolor

		res.append(layer)
		res.append([nexts, u, nextv])
		layer = [nextv]
		visited.add(nextv)

		state[3] = nexti + 1
		stack.append([nextv, nexts, u, 0])

	res.append(layer)
	return res if not hasnextcolor else None

def colorize(s, c):
	if color[s] != -1: return
	global totalcolors
	totalcolors += 1
	color[s] = c
	deg[c] += 1
	q = deque()
	q.append(s)
	while q:
		u = q.popleft()
		for stair in to[u]:
			(v1, v2) = stairs[stair]
			v = v1 if v2 == u else v2
			if color[v] != -1: continue
			color[v] = c
			deg[c] += 1
			q.append(v)

def run():
	global to, color, deg, priority
	n, m = readarray(int)
	to = [[] for i in xrange(n)]
	color = [-1] * n
	deg = [0] * n
	for i in xrange(m):
		u, v = sorted(readarray(lambda x: int(x) - 1))
		stairs.append((u, v))
		to[u].append(i)
		to[v].append(i)
	for i in xrange(n):
		colorize(i, i)

	deg[0] = 100500
	priority = sorted(range(n), lambda x, y: deg[y] - deg[x])[:totalcolors]
	res = doit()
	if res is None:
		print "NO"
		return

	print "YES"
	print len(res) / 2
	for i, line in enumerate(res):
		if i % 2 == 0:
			print len(line),
		print " ".join(map(lambda x: str(x + 1), line))

run()