import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class D {
	private static int n, k;
	private static int[] a;

	public static void main(String[] args) {
		n = ini();
		k = ini();
		a = ina(n);

		Arrays.sort(a);

		int MX = (int)2e5+5;
		int[] count = new int[MX];
		long[] steps = new long[MX];

		for(int i=0; i<n; i++) {
			int v = a[i];
			long st = 0;
			while(true) {
				if (count[v]<k) {
					count[v]++;
					steps[v]+=st;
				}
				if (v==0) break;
				v/=2;
				st++;
			}
		}
		long ans = (long)1e15;
		for(int i=0; i<MX; i++) {
			if (count[i]==k) {
				ans = Math.min(ans, steps[i]);
			}
		}
		println(ans);

//		int[] map = new int[MX];
//		for(int x: a) {
//			map[x]++;
//		}
//
//		int[] ans = new int[MX];
//		int[] track = new int[MX];
//
//		for(int i=0; i<MX; i++) {
//			int temp = i;
//			int count = 0;
//			while(true) {
//				if (track[temp]+count*map[i]<=k) {
//					ans[temp] += count*map[i];
//					track[temp]+=map[i];
//				} else {
//					ans[temp] += count*
//				}
//				temp/=2;
//				count++;
//				if (temp==0) {
//					ans[0] += count;
//					track[0]++;
//					break;
//				}
//			}
//
//		}
//		for(int i=0; i<10; i++) {
//			println(i+" "+track[i]+" "+ans[i]);
//		}
//
//		int sol = (int)1e9;
//		for(int i=0; i<MX; i++) {
//			if (track[i]>=k) {
//				sol = Math.min(sol, ans[i]);
//			}
//		}
//		println(sol);
		out.flush();
		out.close();

	}

	//NONPROBLEM CODE

	private static InputReader in = new InputReader(System.in);
	private static PrintWriter out = new PrintWriter(System.out);

	private static class InputReader {

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;

		public InputReader(InputStream st) {
			this.stream = st;
		}

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public String readString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

	}

	//INPUT SHORTCUTS

	private static int[] ina(int n) {
		int[] temp = new int[n];
		for (int i = 0; i < n; i++) {
			temp[i] = in.nextInt();
		}
		return temp;
	}

	private static int ini() {
		return in.nextInt();
	}

	//OTHER SHORTCUTS
	public static void sort(int[] a) {
		Arrays.sort(a);
	}

	//PRINT SHORTCUTS

	private static void println(Object... o) {
		for (Object x : o) {
			out.write(x + " ");
		}
		out.write("\n");
		out.flush();
	}

	private static void print(Object... o) {
		for (Object x : o) {
			out.write(x + " ");
		}
		out.flush();
	}

	private static void debug(Object... o) {
		for (Object x : o) {
			out.write(x + " ");
		}
		out.write("\n");
		out.flush();
	}
}


import java.util.Scanner;

public class LinksAndPearls {

	public static void main(String[] args) {
		Scanner scan = new Scanner (System.in);
		String chain = scan.nextLine();
		int len = chain.length();
		chain = chain.replaceAll("o", "");
		int o = len-chain.length();
		int dash = chain.length();
		if(o>0) {
		if((dash==0) || (o==1) || ((dash%o==0 && dash>=o) && o>1)) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	} else {
		System.out.println("YES");
	}

	}}


import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class A {
    static MyScanner sc;
    static PrintWriter pw;

    public static void main(String[] args) throws Throwable {
        sc = new MyScanner();
        pw = new PrintWriter(System.out);

        double x = sc.nextDouble();
        double y = sc.nextDouble();
        double z = sc.nextDouble();

        boolean greater = x > 1 || y > 1 || z > 1;
        String[] exp =
                {"x^y^z", "x^z^y", "(x^y)^z", "(x^z)^y",
                        "y^x^z", "y^z^x", "(y^x)^z", "(y^z)^x",
                        "z^x^y", "z^y^x", "(z^x)^y", "(z^y)^x",};

        double[] vals = new double[12];

        if (greater) {
            Arrays.fill(vals, -1e18);
            if (x > 1) {
                vals[0] = z * Math.log(y) + Math.log(Math.log(x));
                vals[1] = y * Math.log(z) + Math.log(Math.log(x));
                vals[2] = Math.log(y) + Math.log(z) + Math.log(Math.log(x));
            }
            if (y > 1) {
                vals[4] = z * Math.log(x) + Math.log(Math.log(y));
                vals[5] = x * Math.log(z) + Math.log(Math.log(y));
                vals[6] = Math.log(x) + Math.log(z) + Math.log(Math.log(y));
            }
            if (z > 1) {
                vals[8] = y * Math.log(x) + Math.log(Math.log(z));
                vals[9] = x * Math.log(y) + Math.log(Math.log(z));
                vals[10] = Math.log(x) + Math.log(y) + Math.log(Math.log(z));
            }
            String ans = "";
            double mx = -2e18;
            for (int i = 0; i < 12; i++)
                if (vals[i] > mx) {
                    mx = vals[i];
                    ans = exp[i];
                }
            pw.println(ans);

        } else {
            Arrays.fill(vals, 1e18);

            vals[0] = z * Math.log(y) + Math.log(Math.log(1 / x));
            vals[1] = y * Math.log(z) + Math.log(Math.log(1 / x));
            vals[2] = Math.log(y) + Math.log(z) + Math.log(Math.log(1 / x));
            vals[4] = z * Math.log(x) + Math.log(Math.log(1 / y));
            vals[5] = x * Math.log(z) + Math.log(Math.log(1 / y));
            vals[6] = Math.log(x) + Math.log(z) + Math.log(Math.log(1 / y));
            vals[8] = y * Math.log(x) + Math.log(Math.log(1 / z));
            vals[9] = x * Math.log(y) + Math.log(Math.log(1 / z));
            vals[10] = Math.log(x) + Math.log(y) + Math.log(Math.log(1 / z));

            String ans = "";
            double mn = 2e18;
            for (int i = 0; i < 12; i++)
                if (vals[i] < mn) {
                    mn = vals[i];
                    ans = exp[i];
                }
            pw.println(ans);

        }

        pw.flush();
        pw.close();
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}


import java.util.*;
import java.io.*;
public class SmallestNumber {
    static BufferedReader br;
    static int[] n;
    static char[] operations;
    public static void main(String[] args) {
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            init();
            System.out.println(solve());
            br.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    private static void init() throws IOException {
    	n = new int[4];
    	operations = new char[3];
    	StringTokenizer st = new StringTokenizer(br.readLine());
    	for(int i = 0; i < 4; i++)
    		n[i] = Integer.parseInt(st.nextToken());
    	st = new StringTokenizer(br.readLine());
    	for(int i = 0; i < 3; i++)
    		operations[i] = st.nextToken().charAt(0);
    }
    private static String solve() {
    	int[] total;
    	if(operations[0] == '*' && operations[1] == '*' && operations[2] == '*') {
    		long l = n[0] * n[1] * n[2];
    		return String.valueOf(l * n[3]);
    	}
    	else if(operations[0] == '+' && operations[1] == '*' && operations[2] == '*') {
    		total = new int[6];
    		for(int i = 0; i < 6; i++) {
    			if(i == 0) total[i] = (n[0] + n[1]) * n[2] * n[3];
    			else if(i == 1) total[i] = (n[0] + n[2]) * n[1] * n[3];
    			else if(i == 2) total[i] = (n[0] + n[3]) * n[1] * n[2];
    			else if(i == 3) total[i] = (n[1] + n[2]) * n[0] * n[3];
    			else if(i == 4) total[i] = (n[1] + n[3]) * n[0] * n[2];
    			else total[i] = (n[2] + n[3]) * n[0] * n[1];
    		}
    	}
    	else if(operations[0] == '*' && operations[1] == '+' && operations[2] == '*') {
    		total = new int[24];
    		for(int i = 0; i < 24; i++) {
    			if(i == 0) total[i] = (n[0] * n[2] + n[3]) * n[1];
    			else if(i == 1) total[i] = (n[0] * n[3] + n[2]) * n[1];
    			else if(i == 2) total[i] = (n[0] * n[1] + n[3]) * n[2];
    			else if(i == 3) total[i] = (n[0] * n[3] + n[1]) * n[2];
    			else if(i == 4) total[i] = (n[0] * n[1] + n[2]) * n[3];
    			else if(i == 5) total[i] = (n[0] * n[2] + n[1]) * n[3];
    			else if(i == 6) total[i] = (n[1] * n[2] + n[3]) * n[0];
    			else if(i == 7) total[i] = (n[1] * n[3] + n[2]) * n[0];
    			else if(i == 8) total[i] = (n[1] * n[0] + n[3]) * n[2];
    			else if(i == 9) total[i] = (n[1] * n[3] + n[0]) * n[2];
    			else if(i == 10) total[i] = (n[1] * n[0] + n[2]) * n[3];
    			else if(i == 11) total[i] = (n[1] * n[2] + n[0]) * n[3];
    			else if(i == 12) total[i] = (n[2] * n[1] + n[3]) * n[0];
    			else if(i == 13) total[i] = (n[2] * n[3] + n[1]) * n[0];
    			else if(i == 14) total[i] = (n[2] * n[0] + n[3]) * n[1];
    			else if(i == 15) total[i] = (n[2] * n[3] + n[0]) * n[1];
    			else if(i == 16) total[i] = (n[2] * n[0] + n[1]) * n[3];
    			else if(i == 17) total[i] = (n[2] * n[1] + n[0]) * n[3];
    			else if(i == 18) total[i] = (n[3] * n[1] + n[2]) * n[0];
    			else if(i == 19) total[i] = (n[3] * n[2] + n[1]) * n[0];
    			else if(i == 20) total[i] = (n[3] * n[0] + n[2]) * n[1];
    			else if(i == 21) total[i] = (n[3] * n[2] + n[0]) * n[1];
    			else if(i == 22) total[i] = (n[3] * n[0] + n[1]) * n[2];
    			else total[i] = (n[3] * n[1] + n[0]) * n[2];
    		}
    	}
    	else if(operations[0] == '*' && operations[1] == '*' && operations[2] == '+') {
    		total = new int[3];
    		for(int i = 0; i < 3; i++) {
    			if(i == 0) total[i] = n[0] * n[1] + n[2] * n[3];
    			else if(i == 1) total[i] = n[0] * n[2] + n[1] * n[3];
    			else total[i] = n[0] * n[3] + n[1] * n[2];
    		}
    	}
    	else if(operations[0] == '*' && operations[1] == '+' && operations[2] == '+') {
    		total = new int[6];
    		for(int i = 0; i < 6; i++) {
    			if(i == 0) total[i] = n[0] * n[1] + n[2] + n[3];
    			else if(i == 1) total[i] = n[0] * n[2] + n[1] + n[3];
    			else if(i == 2) total[i] = n[0] * n[3] + n[1] + n[2];
    			else if(i == 3) total[i] = n[1] * n[2] + n[0] + n[3];
    			else if(i == 4) total[i] = n[1] * n[3] + n[0] + n[2];
    			else total[i] = n[2] * n[3] + n[0] + n[1];
    		}
    	}
    	else if(operations[0] == '+' && operations[1] == '*' && operations[2] == '+') {
    		total = new int[30];
    		for(int i = 0; i < 30; i++) {
    			if(i == 0) total[i] = n[2] * (n[0] + n[1]) + n[3];
    			else if(i == 1) total[i] = (n[0] + n[1]) * n[3] + n[2];
    			else if(i == 2) total[i] = (n[0] + n[2]) * n[1] + n[3];
    			else if(i == 3) total[i] = (n[0] + n[2]) * n[3] + n[1];
    			else if(i == 4) total[i] = (n[0] + n[3]) * n[1] + n[2];
    			else if(i == 5) total[i] = (n[0] + n[3]) * n[2] + n[1];
    			else if(i == 6) total[i] = (n[1] + n[0]) * n[2] + n[3];
    			else if(i == 7) total[i] = (n[1] + n[0]) * n[3] + n[2];
    			else if(i == 8) total[i] = (n[1] + n[2]) * n[0] + n[3];
    			else if(i == 9) total[i] = (n[1] + n[2]) * n[3] + n[0];
    			else if(i == 10) total[i] = (n[1] + n[3]) * n[0] + n[2];
    			else if(i == 11) total[i] = (n[1] + n[3]) * n[2] + n[0];
    			else if(i == 12) total[i] = (n[2] + n[0]) * n[1] + n[3];
    			else if(i == 13) total[i] = (n[2] + n[0]) * n[3] + n[1];
    			else if(i == 14) total[i] = (n[2] + n[1]) * n[0] + n[3];
    			else if(i == 15) total[i] = (n[2] + n[1]) * n[3] + n[0];
    			else if(i == 16) total[i] = (n[2] + n[3]) * n[0] + n[1];
    			else if(i == 17) total[i] = (n[2] + n[3]) * n[1] + n[0];
    			else if(i == 18) total[i] = (n[3] + n[2]) * n[0] + n[1];
    			else if(i == 19) total[i] = (n[3] + n[2]) * n[1] + n[0];
    			else if(i == 20) total[i] = (n[3] + n[1]) * n[0] + n[2];
    			else if(i == 21) total[i] = (n[3] + n[1]) * n[2] + n[0];
    			else if(i == 22) total[i] = (n[3] + n[0]) * n[1] + n[2];
    			else if(i == 23) total[i] = n[0] * n[1] + (n[2] + n[3]);
    			else if(i == 24) total[i] = n[0] * n[2] + (n[1] + n[3]);
    			else if(i == 25) total[i] = n[0] * n[3] + (n[1] + n[2]);
    			else if(i == 26) total[i] = n[1] * n[2] + (n[0] + n[3]);
    			else if(i == 27) total[i] = n[1] * n[3] + (n[0] + n[2]);
    			else if(i == 28) total[i] = n[2] * n[3] + (n[0] + n[1]);
    			else total[i] = (n[3] + n[0]) * n[2] + n[1];
    		}
    	}
    	else if(operations[0] == '+' && operations[1] == '+' && operations[2] == '*') {
    		total = new int[7];
    		for(int i = 0; i < 7; i++) {
    			if(i == 0) total[i] = (n[1] + n[2] + n[3]) * n[0];
    			else if(i == 1) total[i] = (n[0] + n[2] + n[3]) * n[1];
    			else if(i == 2) total[i] = (n[0] + n[1] + n[3]) * n[2];
    			else if(i == 3) total[i] = (n[0] + n[1] + n[2]) * n[3];
    			else if(i == 4) total[i] = (n[0] + n[1]) * (n[2] + n[3]);
    			else if(i == 5) total[i] = (n[0] + n[2]) * (n[1] + n[3]);
    			else total[i] = (n[0] + n[3]) * (n[1] + n[2]);
    		}
    	}
    	else
    		return String.valueOf(n[0] + n[1] + n[2] + n[3]);
//    	System.out.println(Arrays.toString(total));
    	Arrays.sort(total);
//    	System.out.println(Arrays.toString(total));
		return String.valueOf(total[0]);
    }
}


import java.util.Scanner;

public class HitBall203D {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		double a, b, m;
		a = in.nextInt();
		b = in.nextInt();
		m = in.nextInt();
		double vx, vy, vz;
		vx = in.nextInt();
		vy = in.nextInt();
		vz = in.nextInt();
		double t = -1 * m / vy;
		double x = t * vx + a / 2;
		double z = t * vz;
		while (z - 2 * b >= 0)
			z -= 2 * b;
		if (z > b)
			z = 2 * b - z;
		if (x < 0) {
			while (x < 0)
				x += 2 * a;
		} else {
			while (x - 2 * a >= 0)
				x -= 2 * a;
		}
		if (x > a)
			x = 2 * a - x;
		System.out.printf("%f %f\n", x, z);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.StringTokenizer;

public class TaskC {
    public static String doMain(Reader reader) throws IOException {
        MyReader in = new MyReader(reader);
        int n = in.nextInt();
        int p = in.nextInt();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; n - i * p >= i; ++i) {
            int count = check(n - p * i);
            if (count > i){
                continue;
            }
            return i+"";
        }
        return "-1";
    }

    private static int check(int n) {
        int answer = 0;
        while (n > 0) {
            answer += n % 2;
            n /= 2;
        }
        return answer;
    }

    public static void main(String[] args) throws IOException {
        String result = doMain(new InputStreamReader(System.in));
        System.out.println(result);
    }

    static class MyReader {
        BufferedReader bf;

        StringTokenizer st;

        String last;

        MyReader(Reader reader) throws IOException {
            bf = new BufferedReader(reader);
            readNextLine();
        }

        String nextToken() throws IOException {
            while (!st.hasMoreTokens()) {
                readNextLine();
            }
            return st.nextToken();
        }

        void readNextLine() throws IOException {
            last = bf.readLine();
            if (last == null) last = "";
            st = new StringTokenizer(last);
        }

        String nextLine() throws IOException {
            String s = last;
            readNextLine();
            return s;
        }

        long nextLong() throws IOException {
            return Long.parseLong(nextToken());
        }

        int nextInt() throws IOException {
            return Integer.parseInt(nextToken());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(nextToken());
        }

        int[] readIntArray(int n) throws IOException {
            int[] answer = new int[n];
            for (int i = 0; i < n; ++i) {
                answer[i] = nextInt();
            }
            return answer;
        }

        long[] readLongArray(int n) throws IOException {
            long[] answer = new long[n];
            for (int i = 0; i < n; ++i) {
                answer[i] = nextLong();
            }
            return answer;
        }

        double[] readDoubleArray(int n) throws IOException {
            double[] answer = new double[n];
            for (int i = 0; i < n; ++i) {
                answer[i] = nextDouble();
            }
            return answer;
        }
    }
}


import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.print((n+1)/36+" "+(n+1)%36/3);
}
}


import java.util.*;
import java.util.function.*;
import java.io.*;

// you can compare with output.txt and expected out
public class Round818E {
	MyPrintWriter out;
	MyScanner in;

//	final static long FIXED_RANDOM;
//	static {
//		FIXED_RANDOM = System.currentTimeMillis();
//	}
	final static String IMPOSSIBLE = "IMPOSSIBLE";
	final static String POSSIBLE = "POSSIBLE";
	final static String YES = "YES";
	final static String NO = "NO";

    private void initIO(boolean isFileIO) {
        if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
        	try{
	            in = new MyScanner(new FileInputStream("input.txt"));
	            out = new MyPrintWriter(new FileOutputStream("output.txt"));
        	}
        	catch(FileNotFoundException e){
        		e.printStackTrace();
        	}
        }
        else{
    		in = new MyScanner(System.in);
    	    out = new MyPrintWriter(new BufferedOutputStream(System.out));
        }
    }

	public static void main(String[] args){
//		Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));

		Round818E sol = new Round818E();
		sol.run();
    }

	private void run() {
		boolean isDebug = false;
		boolean isFileIO = true;
		boolean hasMultipleTests = false;

		initIO(isFileIO);

		//test();

		int t = hasMultipleTests? in.nextInt() : 1;

	    for (int i = 1; i <= t; ++i) {
	    	if(isDebug){
		    	out.printf("Test %d\n", i);
	    	}

	    	getInput();

	    	solve();

	    	printOutput();
	    }

	    in.close();
	    out.close();
	}

	static long MOD = 1_000_000_007;

	void test() {
		for(int i=2; i<=100; i++) {
			n = i;
			long[] compare = new long[n+1];
			long expected = 0;
			for(int a=1; a<=n; a++) {
				for(int b=1; b<=n; b++) {
					long c = n-a-b;
					if(c < 0)
						continue;
					int g = gcd(a, b);
					long gg = gcd(c, g);
					expected += gg*(c/gg)*(g/gg);
					compare[g] += gg*(c/gg)*(g/gg);
				}
			}
			solve();
			if(expected != ans) {
				solve();
			}

		}
	}

	// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
	int n;
	void getInput() {
		n = in.nextInt();
	}

	void printOutput() {
		out.printlnAns(ans);
	}

	long[] check;
	long ans;
	void solve(){
		// sum lcm(c, gcd(a, b)) for a+b+c = n

		// for each g = gcd(a, b),

		// g = 1
		// lcm = c = n-a-b, so need to count #(a, b) s.t. gcd(a,b)=1 and sum of a+b for such pairs

		// g = 2
		// a = 2a', b = 2b'
		// lcm = c if 2 | n, 2c otherwise

		// g = 3
		// same strategy

		// gcd(g, n - ga' - gb') = gcd(g, n) = k
		// lcm(g, n - ga' - gb') = g*(n-ga'-gb')*k --- i.e., only need #(a, b) and sum of a+b

		// given s,
		// for each a,
		// want to count #b s.t. gcd(a, b) = 1, a + b <= s, b < a
		// for this, simply generate all divisors and exclude them

//		ArrayList<Integer>[] divisors = new ArrayList[n+1];
//		ArrayList<Long>[] prefixSum = new ArrayList[n+1];

//		for(int i=2; i<=n; i++)
//			divisors[i] = new ArrayList<Integer>();
//		for(int i=2; i<=n; i++) {
//			if(divisors[i].isEmpty()) {
//				divisors[i].add(1);
//				divisors[i].add(i);
//				// i*i <= n
//				if(n/i >= i) {
//					for(int j=i*i; j<=n; j+=i)
//						if(divisors[j].isEmpty())
//							divisors[j].add(i);
//				}
//			}
//			else {
//				int prime = divisors[i].remove(0);
//				int maxPrime = 1;
//				{
//					int m = i/prime;
//					while(m % prime == 0) {
//						m /= prime;
//						maxPrime *= prime;
//					}
//				}
//				for(int divisor: divisors[i/prime]) {
//					if(divisor % maxPrime == 0)
//						divisors[i].add(divisor*prime);
//					divisors[i].add(divisor);
//				}
//				Collections.sort(divisors[i]);
//			}
//			prefixSum[i] = new ArrayList<Long>();
//			long sum = 0;
//			for(int divisor: divisors[i]){
//				sum += divisor;
//				prefixSum[i].add(sum);
//			}
//		}

		ArrayList<Integer>[] primeFactors = new ArrayList[n+1];
		for(int i=2; i<=n; i++)
			primeFactors[i] = new ArrayList<Integer>();

//		int[][] prefixCnt = new int[n+1][];
//		long[][] prefixSum = new long[n+1][];

		for(int i=2; i<=n; i++) {
			if(primeFactors[i].isEmpty()) {
				primeFactors[i].add(i);
				// i*i <= n
				if(n/i >= i) {
					for(int j=i*i; j<=n; j+=i)
						if(primeFactors[j].isEmpty())
							primeFactors[j].add(i);
				}
			}
			else {
				int prime = primeFactors[i].get(0);
				int rest = i/prime;
				while(rest % prime == 0)
					rest /= prime;
				if(rest > 1)
					for(int factor: primeFactors[rest])
						primeFactors[i].add(factor);
			}
//			int N = n/i;
//			int[] cnt = new int[N+1];
//			long[] sum = new long[N+1];
//			prefixCnt[i] = cnt;
//			prefixSum[i] = sum;
//			for(int j=1; j<=N; j++) {
//				cnt[j] = cnt[j-1];
//				sum[j] = sum[j-1];
//				if(j % i == 0) {
//					cnt[j]++;
//					sum[j]+=j;
//				}
//			}
		}

		ans = 0;
		check = new long[n+1];
		for(long g=1; g<=n; g++) {
			if(g*2 + 1 > n)
				break;
			long cnt = 0;
			long sum = 0;
			// 1) a < b

			// want to count #b' s.t. gcd(a', b') = 1, a' + b' <= s, b' < a'
			// g(a'+b')+1 <= n
			for(int ap=2; ap<=n; ap++) {
				if(g*(ap+1) + 1 > n)
					break;

				long maxBp = Math.min(ap-1, (n-1)/g - ap);
				long currCnt = maxBp;
				sum += maxBp*(maxBp+1)/2 % MOD;

				int k = primeFactors[ap].size();
				for(int mask=1; mask<(1<<k); mask++) {
					long curr = 1;
					int sign = 1;
					for(int pos=0; pos<k; pos++) {
						if((mask & (1<<pos)) > 0) {
							curr *= primeFactors[ap].get(pos);
							sign *= -1;
						}
					}
					// s*curr + g*ap + 1 <= n
					long s = Math.min((ap-1)/curr, (n-1 - g*ap)/curr/g);
//					currCnt += prefixCnt[curr][s] * sign;
//					sum += prefixSum[curr][s] * sign;
					currCnt += s * sign;
					sum += curr * s * (s+1)/2 * sign;
				}

//				HashSet<Integer> bad = new HashSet<>();
//				for(int prime: primeFactors[ap]) {
//					for(int i=1; i<=n; i++) {
//						int bp = prime*i;
//						if(bp >= ap || g*(ap+bp) + 1 > n)
//							break;
//						if(!bad.contains(bp)) {
//							bad.add(bp);
//							currCnt--;
//							sum -= bp;
//						}
//					}
//				}

				cnt += currCnt;
				sum += currCnt * ap;
				sum %= MOD;

//				int k = divisors[ap].size();
//				int lo = 0;
//				int hi = k-2;
//				while(lo < hi) {
//					int mid = (lo+hi+1)/2;
//					int bp = divisors[ap].get(mid);
//					if(g*(ap+bp) + 1 > n)
//						hi = mid-1;
//					else
//						lo = mid;
//				}
//				// g*(ap+maxBp)+1 <= n
//				long maxBp = Math.min(ap-1, (n-1)/g - ap);
//				// g(1+...+maxBp)
//				long currCnt = maxBp - lo; // 1 is always ok
//				cnt += currCnt;
//				sum += currCnt * ap % MOD;
//				sum += maxBp*(maxBp+1)/2 % MOD;
//				sum -= (prefixSum[ap].get(lo)-1) % MOD;
			}

			// then *2
			cnt *= 2;
			sum *= g*2;

			// 2) a = b = g
			cnt ++;
			sum += g*2;

			cnt %= MOD;
			sum %= MOD;
			if(sum < 0)
				sum += MOD;

			// (1, 1)
			// (1, 2), (1, 3)
			// (2, 1), (3, 1)

			// n = 6
			// (1, 1)
			// (1, 2)
			// (1, 3), (2, 3)
			// (1, 4)
			// cnt = 1 + 4*2 = 9
			// sum = 2 + 17*2 = 36
			// 4 + (3 + 2 + 1 + 1)*2 = 18

			// (2, 2)
			// 2

			// 6 * 9 = 54
			// 36

			// lcm(g, n - ga' - gb') = g/k*(n-ga'-gb')/k*k --- i.e., only need #(a, b) and sum of a+b
			check[(int)g] -= ans;
			long k = gcd(g, n);
			ans += g*n/k*cnt % MOD;
			ans -= g/k*sum % MOD;
			check[(int)g] += ans;
		}
		ans %= MOD;
		if(ans < 0)
			ans += MOD;
	}

	static long gcd(long a, long b){
		if(a < b){
			long temp = b;
			b = a;
			a = temp;
		}
		// a > b
		while (b > 0) {
			long r = a % b;
			a = b;
			b = r;
		}
		return a;
	}

	static int gcd(int a, int b){
		if(a < b){
			int temp = b;
			b = a;
			a = temp;
		}
		// a > b
		while (b > 0) {
			int r = a % b;
			a = b;
			b = r;
		}
		return a;
	}

//	Optional<T> solve()
//	return Optional.empty();

	static class Pair implements Comparable<Pair>{
		final static long FIXED_RANDOM = System.currentTimeMillis();
		int first, second;
		public Pair(int first, int second) {
			this.first = first;
			this.second = second;
		}

		@Override
		public int hashCode() {
			// http://xorshift.di.unimi.it/splitmix64.c
			long x = first;
			x <<= 32;
			x += second;
			x += FIXED_RANDOM;
			x += 0x9e3779b97f4a7c15l;
			x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
			x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
			return (int)(x ^ (x >> 31));
		}
		@Override
		public boolean equals(Object obj) {
//			if (this == obj)
//				return true;
//			if (obj == null)
//				return false;
//			if (getClass() != obj.getClass())
//				return false;
			Pair other = (Pair) obj;
			return first == other.first && second == other.second;
		}
		@Override
		public String toString() {
			return "[" + first + "," + second + "]";
		}

		@Override
		public int compareTo(Pair o) {
			int cmp = Integer.compare(first, o.first);
			return cmp != 0? cmp: Integer.compare(second, o.second);
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		// 32768?
		public MyScanner(InputStream is, int bufferSize) {
			br = new BufferedReader(new InputStreamReader(is), bufferSize);
		}

		public MyScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
			// br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
		}

		public void close() {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine(){
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

		int[][] nextMatrix(int n, int m) {
			return nextMatrix(n, m, 0);
		}

		int[][] nextMatrix(int n, int m, int offset) {
			int[][] mat = new int[n][m];
			for(int i=0; i<n; i++) {
				for(int j=0; j<m; j++) {
					mat[i][j] = nextInt()+offset;
				}
			}
			return mat;
		}

		int[][] nextTransposedMatrix(int n, int m){
			return nextTransposedMatrix(n, m, 0);
		}

		int[][] nextTransposedMatrix(int n, int m, int offset){
			int[][] mat = new int[m][n];
			for(int i=0; i<n; i++) {
				for(int j=0; j<m; j++) {
					mat[j][i] = nextInt()+offset;
				}
			}
			return mat;
		}

		int[] nextIntArray(int len) {
			return nextIntArray(len, 0);
		}
		int[] nextIntArray(int len, int offset){
	    	int[] a = new int[len];
			for(int j=0; j<len; j++)
	    		a[j] = nextInt()+offset;
	    	return a;
		}

		long[] nextLongArray(int len) {
			return nextLongArray(len, 0);
		}
		long[] nextLongArray(int len, int offset){
	    	long[] a = new long[len];
			for(int j=0; j<len; j++)
	    		a[j] = nextLong()+offset;
	    	return a;
		}

		String[] nextStringArray(int len) {
			String[] s = new String[len];
			for(int i=0; i<len; i++)
				s[i] = next();
			return s;
		}
	}

	public static class MyPrintWriter extends PrintWriter{
		public MyPrintWriter(OutputStream os) {
			super(os);
		}

//		public <T> void printlnAns(Optional<T> ans) {
//			if(ans.isEmpty())
//				println(-1);
//			else
//				printlnAns(ans.get());
//		}

		public void printlnAns(OptionalInt ans) {
			println(ans.orElse(-1));
		}

		public void printlnAns(long ans) {
			println(ans);
		}

		public void printlnAns(int ans) {
			println(ans);
		}

		public void printlnAns(boolean ans) {
			if(ans)
				println(YES);
			else
				println(NO);
		}

		public void printAns(long[] arr){
			if(arr != null && arr.length > 0){
				print(arr[0]);
				for(int i=1; i<arr.length; i++){
					print(" ");
					print(arr[i]);
				}
			}
		}
		public void printlnAns(long[] arr){
			printAns(arr);
			println();
		}

		public void printAns(int[] arr){
			if(arr != null && arr.length > 0){
				print(arr[0]);
				for(int i=1; i<arr.length; i++){
					print(" ");
					print(arr[i]);
				}
			}
		}
		public void printlnAns(int[] arr){
			printAns(arr);
			println();
		}

		public <T> void printAns(ArrayList<T> arr){
			if(arr != null && arr.size() > 0){
				print(arr.get(0));
				for(int i=1; i<arr.size(); i++){
					print(" ");
					print(arr.get(i));
				}
			}
		}
		public <T> void printlnAns(ArrayList<T> arr){
			printAns(arr);
			println();
		}

		public void printAns(int[] arr, int add){
			if(arr != null && arr.length > 0){
				print(arr[0]+add);
				for(int i=1; i<arr.length; i++){
					print(" ");
					print(arr[i]+add);
				}
			}
		}
		public void printlnAns(int[] arr, int add){
			printAns(arr, add);
			println();
		}

		public void printAns(ArrayList<Integer> arr, int add) {
			if(arr != null && arr.size() > 0){
				print(arr.get(0)+add);
				for(int i=1; i<arr.size(); i++){
					print(" ");
					print(arr.get(i)+add);
				}
			}
		}

		public void printlnAns(ArrayList<Integer> arr, int add){
			printAns(arr, add);
			println();
		}

		public void printlnAnsSplit(long[] arr, int split){
			if(arr != null){
				for(int i=0; i<arr.length; i+=split){
					print(arr[i]);
					for(int j=i+1; j<i+split; j++){
						print(" ");
						print(arr[j]);
					}
					println();
				}
			}
		}

		public void printlnAnsSplit(int[] arr, int split){
			if(arr != null){
				for(int i=0; i<arr.length; i+=split){
					print(arr[i]);
					for(int j=i+1; j<i+split; j++){
						print(" ");
						print(arr[j]);
					}
					println();
				}
			}
		}

		public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
			if(arr != null && !arr.isEmpty()){
				for(int i=0; i<arr.size(); i+=split){
					print(arr.get(i));
					for(int j=i+1; j<i+split; j++){
						print(" ");
						print(arr.get(j));
					}
					println();
				}
			}
		}
	}

	static private void permutateAndSort(long[] a) {
		int n = a.length;
		Random R = new Random(System.currentTimeMillis());
		for(int i=0; i<n; i++) {
			int t = R.nextInt(n-i);
			long temp = a[n-1-i];
			a[n-1-i] = a[t];
			a[t] = temp;
		}
		Arrays.sort(a);
	}

	static private void permutateAndSort(int[] a) {
		int n = a.length;
		Random R = new Random(System.currentTimeMillis());
		for(int i=0; i<n; i++) {
			int t = R.nextInt(n-i);
			int temp = a[n-1-i];
			a[n-1-i] = a[t];
			a[t] = temp;
		}
		Arrays.sort(a);
	}

	static private int[][] constructChildren(int n, int[] parent, int parentRoot){
		int[][] childrens = new int[n][];

		int[] numChildren = new int[n];
		for(int i=0; i<parent.length; i++) {
			if(parent[i] != parentRoot)
				numChildren[parent[i]]++;
		}

		for(int i=0; i<n; i++) {
			childrens[i] = new int[numChildren[i]];
		}

		int[] idx = new int[n];
		for(int i=0; i<parent.length; i++) {
			if(parent[i] != parentRoot)
				childrens[parent[i]][idx[parent[i]]++] = i;
		}

		return childrens;
	}

	static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
		int[] inDegree = new int[n];
		int[] outDegree = new int[n];
		for(int i=0; i<e.length; i++) {
			int u = e[i][0];
			int v = e[i][1];
			outDegree[u]++;
			inDegree[v]++;
		}

		int[][] inNeighbors = new int[n][];
		int[][] outNeighbors = new int[n][];
		for(int i=0; i<n; i++) {
			inNeighbors[i] = new int[inDegree[i]];
			outNeighbors[i] = new int[outDegree[i]];
		}

		for(int i=0; i<e.length; i++) {
			int u = e[i][0];
			int v = e[i][1];
			outNeighbors[u][--outDegree[u]] = v;
			inNeighbors[v][--inDegree[v]] = u;
		}

		return new int[][][] {inNeighbors, outNeighbors};
	}

	static private int[][] constructNeighborhood(int n, int[][] e) {
		int[] degree = new int[n];
		for(int i=0; i<e.length; i++) {
			int u = e[i][0];
			int v = e[i][1];
			degree[u]++;
			degree[v]++;
		}

		int[][] neighbors = new int[n][];
		for(int i=0; i<n; i++)
			neighbors[i] = new int[degree[i]];

		for(int i=0; i<e.length; i++) {
			int u = e[i][0];
			int v = e[i][1];
			neighbors[u][--degree[u]] = v;
			neighbors[v][--degree[v]] = u;
		}

		return neighbors;
	}

	static private void drawGraph(int[][] e) {
		makeDotUndirected(e);
		try {
			final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
					.redirectOutput(new File("graph.png"))
					.start();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	static private void makeDotUndirected(int[][] e) {
		MyPrintWriter out2 = null;
		 try {
			out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		out2.println("strict graph {");
		for(int i=0; i<e.length; i++){
			out2.println(e[i][0] + "--" + e[i][1] + ";");
		}
		out2.println("}");
		out2.close();
	}

	static private void makeDotDirected(int[][] e) {
		MyPrintWriter out2 = null;
		 try {
			out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		out2.println("strict digraph {");
		for(int i=0; i<e.length; i++){
			out2.println(e[i][0] + "->" + e[i][1] + ";");
		}
		out2.println("}");
		out2.close();
	}

}


/*
 *    Nachiket V Trivedi
 *    DAIICT
 */
import java.util.*;
import java.io.*;
import java.math.*;
public class demo1
{

	public static void main(String[] args)
	{
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		//------Start-----
		long n=in.nextLong();
		int k=in.nextInt();
		TreeSet<Long> al=new TreeSet<Long>();
		for(long i=1;i*i<=n;i++)
		{
			if(n%i==0)
			{
				al.add(i);
				al.add(n/i);
			}
		}

		if(al.size()<k)
			out.println("-1");
		else
		{
			int j=0;
			for(long i:al)
			{
				j++;
				if(j==k)
				{
					out.print(i);
					break;
				}
			}
		}
		//-----The End----
		out.close();
	}
	//start writing new static method here

	//My template methods are here--------------------------------------------------
	static boolean[] sieveOfEratosthenes(int n)//#1
	{
		// Create a boolean array "prime[0..n]" and initialize
		// all entries it as true. A value in prime[i] will
		// finally be false if i is Not a prime, else true.
		boolean prime[] = new boolean[n+1];
		for(int i=0;i<n;i++)
			prime[i] = true;

		for(int p = 2; p*p <=n; p++)
		{
			// If prime[p] is not changed, then it is a prime
			if(prime[p] == true)
			{
				// Update all multiples of p
				for(int i = p*2; i <= n; i += p)
					prime[i] = false;
			}
		}
		return prime;

	}
	static TreeSet primeFactors(long n)//#2
	{
		TreeSet<Long> ts=new TreeSet();
		while(n%2==0)
		{
			ts.add((long)2);
			n=n/2;
		}
		for(long i=3;i<=Math.sqrt(n);i+=2)
		{
			while(n%i==0)
			{
				ts.add(i);
				n=n/i;
			}
		}
		if(n>2)
			ts.add(n);
		return ts;
	}
	static boolean isPrime(long num)//#3
	{
		if (num < 2) return false;
		if (num == 2) return true;
		if (num % 2 == 0) return false;
		for (int i = 3; i * i <= num; i += 2)
			if (num % i == 0) return false;
		return true;
	}
	static long modular_exponentiation(long a, long b, long c)// calculates (a^b)%c
	{
		//while calling this function pass a as a%m and IF c in prime then pass b as b%(m-1)..coz of fermet's theorem
		//if c is not prime then pass only b.
		a=a%c;
		if(b == 0)
			return 1;
		if(b == 1)
			return a%c;
		else if( b%2 == 0)                                           //if b is even
		{
			return modular_exponentiation((a *a)%c,b/2,c);
		}
		else                                                                    // if b is odd.
		{
			return (a*modular_exponentiation((a*a%c),b/2,c))%c;
		}
	}
	static int findGCD(int number1, int number2) //complexity O(log(max(n1,n2)))
	{
		if(number2 == 0)
			return number1;
		return findGCD(number2, number1%number2);
	}
	static void extendedEuclid(int A, int B) {
		//gcd(A,B)=Ax+By....this calculates the coefficients...
		//make those variables global and open these comments
		if(B == 0)
		{
			//	        gcd = A;
			//	        x = 1;
			//	        y = 0;
		}
		else
		{
			extendedEuclid(B, A%B);
			//			int temp = x;
			//			x = y;
			//			y = temp - (A/B)*y;
		}
	}

	static void modInverse(int A, int M)
	{
		//A and M must be coprime for modinverse to exist.
		//If M is prime the call modexponentiation(A,M-2,M)
	    extendedEuclid(A,M);
	    //return (x%M+M)%M;    //this is x of Ax+By=GCD from euclid...x may be negative
	}
	static void debug(Object... o)// to print any object like an array
	{
		System.out.println(Arrays.deepToString(o));
	}
	static public ArrayList<ArrayList<Integer>> FindAllsubsets(int[] S)//2^n complexity
	{
		if (S == null)
			return null;
		Arrays.sort(S);
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		for (int i = 0; i < S.length; i++) {
			ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
			//get sets that are already in result
			for (ArrayList<Integer> a : result) {
				temp.add(new ArrayList<Integer>(a));
			}
			//add S[i] to existing sets
			for (ArrayList<Integer> a : temp) {
				a.add(S[i]);
			}
			//add S[i] only as a set
			ArrayList<Integer> single = new ArrayList<Integer>();
			single.add(S[i]);
			temp.add(single);
			result.addAll(temp);
		}
		//add empty set
		result.add(new ArrayList<Integer>());
		return result;
	}
	static int greatestIndexNotExceeding(int[] data, int limit, int lb, int ub)
	{
		final int mid = (lb + ub) / 2;
		// Need to go lower but can't
		if (mid == lb && data[mid] > limit)
			return -1;
		// Found a candidate, and can't go higher
		if (data[mid] <= limit && (mid == ub || data[mid + 1] > limit))
			return mid;
		if (data[mid] <= limit)
			// Consider upper half
			return greatestIndexNotExceeding(data, limit, mid + 1, ub);
		else
			// Consider lower half
			return greatestIndexNotExceeding(data, limit, lb, mid);
	}

	//Pair class is here
	static class Pair implements Comparable<Pair>
	{
		long u;
		long v;
		BigInteger bi;
		public Pair(long u, long v) {
			this.u = u;
			this.v = v;
		}

		public int hashCode() {
			int hu = (int) (u ^ (u >>> 32));
			int hv = (int) (v ^ (v >>> 32));
			return 31 * hu + hv;
		}

		public boolean equals(Object o) {
			Pair other = (Pair) o;
			return u == other.u && v == other.v;
		}

		public int compareTo(Pair other) {
			return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
		}

		public String toString() {
			return "[u=" + u + ", v=" + v + "]";
		}
	}
	//End of My Templates-----------------InputReader class starts from here--------------------------------------------------------------
	public static class InputReader
	{
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream inputstream)
		{
			reader = new BufferedReader(new InputStreamReader(inputstream));
			tokenizer = null;
		}

		public String nextLine()
		{
			String fullLine=null;
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				try
				{
					fullLine=reader.readLine();
				}
				catch (IOException e)
				{
					throw new RuntimeException(e);
				}
				return fullLine;
			}
			return fullLine;
		}
		public String next()
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				try
				{
					tokenizer = new StringTokenizer(reader.readLine());
				}
				catch (IOException e)
				{
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public long nextLong()
		{
			return Long.parseLong(next());
		}
		public int nextInt()
		{
			return Integer.parseInt(next());
		}
	}

}

//---------------------------------------------------------------


import java.util.*;

public class CF560BGetaldIntoArts {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        boolean b = true;

        int a1 = s.nextInt();
        int b1 = s.nextInt();
        int a2 = s.nextInt();
        int b2 = s.nextInt();
        int a3 = s.nextInt();
        int b3 = s.nextInt();

        if(a1 >= Math.max(a2,a3) && b2+b3<=b1) b = true;

        else if(a1 >= Math.max(a2,b3) && b2+a3<=b1) b = true;

        else if(a1 >= Math.max(a3,b2) && b3+a2<=b1) b = true;

        else if(a1 >= Math.max(b2,b3) && a2+a3<=b1) b = true;
        else b = false;

        if(b1 >= Math.max(a2,a3) && b2+b3<=a1) b = true;

        else if(b1 >= Math.max(a2,b3) && b2+a3<=a1) b = true;

        else if(b1>=Math.max(a3,b2) && b3+a2<=a1) b = true;

        else if(b1>=Math.max(b2,b3) && a2+a3<=a1) b = true;

        if(b == false){
            System.out.println("NO");
        }
        else System.out.println("YES");

    }
}


//package com.company;

import java.io.*;
import java.util.*;

public class Main {
    public static class Task {
        public class Number {
            int factNum;
            int[] primeFactorCounts;
            int largestFactor;
            int S = 0;
            public Number(int f, int[] primeFactorCounts) {
                this.factNum = f;
                this.primeFactorCounts = primeFactorCounts;
                for (largestFactor = primeFactorCounts.length - 1; largestFactor >= 0; largestFactor--) {
                    if (primeFactorCounts[largestFactor] != 0) break;
                }
                for (int y: primeFactorCounts)S += y;
            }
            int getL() {
                if (largestFactor == -1) return -1;
                int r = largestFactor;
                primeFactorCounts[r]--;
                if (primeFactorCounts[r] == 0) largestFactor--;
                return r;
            }
        }

        List<Integer> primes;
        int[] factor;

        public void precompute() {
            int n = 5001;
            primes = new ArrayList<>();
            factor = new int[n];
            Arrays.fill(factor, -1);
            for (int i = 2; i < n; ++i) {
                if (factor[i] == -1) {
                    factor[i] = primes.size();
                    primes.add(i);
                }
                for (int j = 0; j < primes.size () && i * primes.get(j) < n; ++j) {
                    int p = primes.get(j);
                    factor[i * p] = j;
                    if (i % p == 0) {
                        break;
                    }
                }
            }
        }

        List<Integer> fact(int x) {
            List<Integer> retL = new ArrayList<>();
            while (x != 1) {
                retL.add(factor[x]);
                x /= primes.get(factor[x]);
            }
            return retL;
        }

        public void solve(Scanner sc, PrintWriter pw) throws IOException {
            precompute();
            int[] primeF = new int[700];
            Number[] numbers = new Number[5001];
//            numbers[0] = new Number(1, Arrays.copyOf(primeF, 700));
            numbers[1] = new Number(1, Arrays.copyOf(primeF, 700));
            for (int i = 2; i <= 5000; i++) {
                List<Integer> f = fact(i);
                for (int y: f) primeF[y]++;
                numbers[i] = new Number(i, Arrays.copyOf(primeF, 700));
            }
//            pw.println(Arrays.toString(numbers[5000].primeFactorCounts));
//            System.err.println(numbers[5000].S);
            Map<Integer, Integer> numToCount = new HashMap<>();
            int n = sc.nextInt();
            for (int i = 0; i < n; i++) {
                int a = sc.nextInt();
                a = Math.max(a, 1);
                numToCount.put(a, numToCount.getOrDefault(a, 0) + 1);
            }
            long total = 0;
            for (Map.Entry<Integer, Integer> en : numToCount.entrySet()) {
                total += (long) en.getValue() * numbers[en.getKey()].S;
            }
            outer:
            while (true) {
                Map<Integer, Integer> kG = new HashMap<>();
                for (Map.Entry<Integer, Integer> en : numToCount.entrySet()) {
                    int k = en.getKey();
                    int v = en.getValue();
                    int lf = numbers[k].largestFactor;
                    if (lf == -1) continue ;
                    kG.put(lf, kG.getOrDefault(lf, 0) + v);
                }
                for (Map.Entry<Integer, Integer> en: kG.entrySet()) {
                    if (n - en.getValue() < en.getValue()) {
                        total -= en.getValue() - (n - en.getValue());
                        Map<Integer, Integer> nC = new HashMap<>();
                        for (Map.Entry<Integer, Integer> en1 : numToCount.entrySet()) {
                            int lf = numbers[en1.getKey()].getL();
                            if (lf == en.getKey()) {
                                nC.put(en1.getKey(), en1.getValue());
                            }
                        }
                        numToCount = nC;
                        continue outer;
                    }
                }
                pw.println(total);
                return;
            }
        }
    }

    static long TIME_START, TIME_END;

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
//        Scanner sc = new Scanner(new FileInputStream("input"));
        PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
//        PrintWriter pw = new PrintWriter(new FileOutputStream("output"));

        Runtime runtime = Runtime.getRuntime();
        long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
        TIME_START = System.currentTimeMillis();
        Task t = new Task();
        t.solve(sc, pw);
        TIME_END = System.currentTimeMillis();
        long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
        pw.close();
        System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
        System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(FileReader s) throws FileNotFoundException {
            br = new BufferedReader(s);
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        public boolean ready() throws IOException {
            return br.ready();
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class A741 {
	static int min;
	static boolean[] visited;
	static int[] adj;
	static long[] cyc;
	public static void main(String[] args) throws IOException{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();

		adj = new int[n];
		visited = new boolean[n];
		cyc = new long[n];
		TreeSet<Integer> set = new TreeSet<>();
		for(int i = 0;i<n;i++)
		{
			adj[i] = sc.nextInt()-1;
			set.add(adj[i]);
		}

		if(set.size()<adj.length)
		{
			System.out.println(-1);
			return;
		}

		for(int i = 0;i<n;i++)
		{
			visited = new boolean[n];
			dfs(i,i,0);
		}

		System.out.println(lcm(cyc));
	}
	static void dfs(int u, int t, int steps){
		if(visited[u])
			if(u==t)
			{
				if(steps%2==0)
					steps = steps/2;

				cyc[t] = steps;
				return;
			}
			else
				return;

		visited[u] = true;

		dfs(adj[u],t,steps+1);
	}
	static long gcd(long a, long b)
	{
	    while (b > 0)
	    {
	        long temp = b;
	        b = a % b; // % is remainder
	        a = temp;
	    }
	    return a;
	}

	static long gcd(long[] input)
	{
	    long result = input[0];
	    for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
	    return result;
	}
	static long lcm(long a, long b)
	{
	    return a * (b / gcd(a, b));
	}

	static long lcm(long[] input)
	{
	    long result = input[0];
	    for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
	    return result;
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s) {	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

		public boolean ready() throws IOException {return br.ready();}

	}
}


import java.io.*;
import java.util.*;

public class R400qE {

  static int mod = 1000000007;

  public static void main(String[] args) {
    InputReader in = new InputReader(System.in);
    PrintWriter w = new PrintWriter(System.out);

    long n = in.nextLong();
    long k = (in.nextLong() + 1) / 2;

    while (n > 1 && k > 0) {
      n = phi(n);
      k--;
    }

    w.println(n % mod);
    w.close();
  }

  static long phi(long n) {
    long result = n;
    for (long p = 2; p * p <= n; ++p) {
      if (n % p == 0) {
        while (n % p == 0)
          n /= p;
        result /= p;
        result *= p - 1;
      }
    }

    if (n > 1) {
      result /= n;
      result *= n - 1;
    }

    return result;
  }

  static int f(int n) {
    if (n == 1) {
      return 1;
    }
    int ans = 0;
    for (int i = 1; i < n; i++) {
      if (gcd(i, n - i) == 1) {
        ans++;
      }
    }
    return ans;
  }

  static int g(int n) {
    int ans = 0;
    for (int i = 1; i <= n; i++) {
      if (n % i == 0) {
        ans += f(n / i);
      }
    }
    return ans;
  }

  public static int gcd(int a, int b) {
    while (b != 0) {
      int t = b;
      b = a % b;
      a = t;
    }
    return a;
  }

  static class InputReader {

    private final InputStream stream;
    private final byte[] buf = new byte[8192];
    private int curChar, snumChars;

    public InputReader(InputStream st) {
      this.stream = st;
    }

    public int read() {
      if (snumChars == -1)
        throw new InputMismatchException();
      if (curChar >= snumChars) {
        curChar = 0;
        try {
          snumChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (snumChars <= 0)
          return -1;
      }
      return buf[curChar++];
    }

    public int nextInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public long nextLong() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      long res = 0;
      do {
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public int[] nextIntArray(int n) {
      int a[] = new int[n];
      for (int i = 0; i < n; i++) {
        a[i] = nextInt();
      }
      return a;
    }

    public String readString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        res.appendCodePoint(c);
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public String nextLine() {
      int c = read();
      while (isSpaceChar(c))
        c = read();
      StringBuilder res = new StringBuilder();
      do {
        res.appendCodePoint(c);
        c = read();
      } while (!isEndOfLine(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private boolean isEndOfLine(int c) {
      return c == '\n' || c == '\r' || c == -1;
    }

  }

}


import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class A487 {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		Solver solver = new Solver();
		solver.solve(1, in, out);
		out.close();
	}

static class Solver {

	int hm, am, dm, hy;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
    	hy = in.nextInt();
    	int ay = in.nextInt();
    	int dy = in.nextInt();
    	hm = in.nextInt();
    	am = in.nextInt();
    	dm = in.nextInt();
    	int hc = in.nextInt();
    	int ac = in.nextInt();
    	int dc = in.nextInt();
    	long ans = Long.MAX_VALUE;
		for (int a = 0; a < 200; a++) {
			for (int d = 0; d < 200; d++) {
				int h = hpToWin(a+ay, d+dy);
				if (h == -1) continue;
				long cost = h*hc + a*ac + d*dc;
				ans = Math.min(ans, cost);
			}
		}
    	System.out.println(ans);
    }

    public int hpToWin(int ay, int dy) {
    	if (ay-dm <= 0) return -1; //impossible
    	if (am-dy <= 0) return 0;

    	double turns = (double)hm / (double)(ay-dm);
    	int turnY = (int) Math.ceil(turns);

    	// so you need turnY+1 and take am-dy per turn
    	return Math.max(0, turnY * (am-dy) + 1 - hy);
    }

	void debug(Object...os) {
		System.err.println(Arrays.deepToString(os));
	}

}

static class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
    public long nextLong() {
        return Long.parseLong(next());
    }
    public double nextDouble() {
        return Double.parseDouble(next());
    }
}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author pigsoft
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            String a = in.nextLine();
            int n = in.nextInt();
            String cw = "^>v<";
            String ccw = "^<v>";
            boolean iscw = false;
            boolean isccw = false;

            int id = 0;
            for (int i = 0; i < 4; i++) {
                if (a.charAt(0) == cw.charAt(i))
                    id = i;
            }
            id = (id + n) % 4;

            if (cw.charAt(id) == a.charAt(2)) {
                iscw = true;
            }

            id = 0;
            for (int i = 0; i < 4; i++) {
                if (a.charAt(0) == ccw.charAt(i))
                    id = i;
            }
            id = (id + n) % 4;
            if (ccw.charAt(id) == a.charAt(2)) {
                isccw = true;
            }

            if (iscw == isccw)
                out.print("undefined");
            else if (iscw)
                out.print("cw");
            else
                out.print("ccw");
        }

    }
}


import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.math.*;
import java.lang.*;
import java.util.stream.Collectors;

import static java.lang.Math.*;

public class Main implements Runnable
{
    static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception
    {
        new Thread(null, new Main(),"Main",1<<27).start();
    }

    public static long gcd(long a, long b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }

    public static long findGCD(long arr[], int n)
    {
        long result = arr[0];
        for (int i = 1; i < n; i++)
            result = gcd(arr[i], result);
        return result;
    }

    static void sortbycolomn(long arr[][], int col)
    {

        Arrays.sort(arr, new Comparator<long[]>() {

            @Override

            public int compare(final long[] entry1,
                               final long[] entry2) {

                if (entry1[col] > entry2[col])
                    return 1;
                else
                    return -1;
            }
        });
    }

    static String sortString(String str) {
        int MAX_CHAR = 256;
        int letters[] = new int[MAX_CHAR];
        for (char x : str.toCharArray()) {

            // 'a'-'a' will be 0, 'b'-'a' will be 1,
            // so for location of character in count
            // array we will do str[i]-'a'.
            letters[x - 'a']++;
        }

        // Traverse the hash array and print
        // characters
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < MAX_CHAR; i++) {
            for (int j = 0; j < letters[i]; j++) {
                sb.append((char) (i + 'a'));
            }
        }
        return sb.toString();
    }
    public int lb(int[] a, int val){
        int min = 0, len = a.length, max = len;
        while(min<max){
            int mid = min + (max-min)/2;
            if(a[mid]>=val){
                max = mid;
            }
            else{
                min = mid+1;
            }
        }
        return max;
    }
    public int ub(int[] a, int val){
        int min = 0, len = a.length, max = len;
        while(min<max){
            int mid = min + (max-min)/2;
            if(a[mid]>val){
                max = mid;
            }
            else {
                min = mid + 1;
            }
        }
        return max;
    }
    public int lb(List<Integer> a, int val){
        int min = 0, len = a.size(), max = len;
        while(min<max){
            int mid = min + (max-min)/2;
            if(a.get(mid)>=val){
                max = mid;
            }
            else{
                min = mid+1;
            }
        }
        return max;
    }
    public int ub(List<Integer> a, int val){
        int min = 0, len = a.size(), max = len;
        while(min<max){
            int mid = min + (max-min)/2;
            if(a.get(mid)>val){
                max = mid;
            }
            else {
                min = mid + 1;
            }
        }
        return max;
    }
    public void run()
    {
        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);
        long n = in.nextLong();
        long prev = n;
        long i = 2;
        while(i*i<=n){
            if(n%i==0){
                n-=i;
//                w.println(n);
                break;
            }
            i++;
        }
        if(n==prev) w.println(1);
        else w.println(1+n/2);
        w.flush();
        w.close();
    }
}


import java.util.*;
public class transformation {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int num1 = scan.nextInt();
        int num2 = scan.nextInt(),k=num2;
        ArrayList<Integer> arr = new ArrayList<>();
        while(num2>num1){
            if(num2%2==0){
                num2=num2/2;
                arr.add(num2);
            }
            else if(num2%10==1){
                num2=num2/10;
                arr.add(num2);
            }
            else
                break;
        }
        if(num1==num2){
            System.out.println("YES");
            System.out.println(arr.size()+1);
            for(int i=arr.size()-1;i>=0;i--){
                System.out.print(arr.get(i)+" ");
            }
            System.out.print(k);
        }
        else
            System.out.println("NO");
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int a1 = kb.nextInt();
        int b1 = kb.nextInt();
        int c1 = kb.nextInt();
        int a2 = kb.nextInt();
        int b2 = kb.nextInt();
        int c2 = kb.nextInt();
        int D = a1*b2-a2*b1;
        if((a1==0&&b1==0&&c1!=0)||(a2==0&&b2==0&&c2!=0))System.out.println(0);
        else if((a1==0&&b1==0&&c1==0)||(a2==0&&b2==0&&c2==0))System.out.println(-1);
        else if(D!=0)System.out.println(1);
        else if(a1*c2==a2*c1&&b1*c2==b2*c1)System.out.println(-1);
        else System.out.println(0);
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String player = "Mahmoud";
        boolean flag = true;

        while (flag) {
            if (player.contains("Mahmoud")) {
                if (n % 2 == 0) {
                    flag = false;
                } else if(n==1){
                    player = "Ehab";
                    flag = false;
                } else {
                    int random = (int) (Math.random() * (n - 2 + 1) + 2) / 2 * 2;
                    n-=random;
                }
            } else if (player.contains("Ehab")) {
                if (n % 2 == 1) {
                    flag = false;
                } else {
                    int random = (int) (Math.random() * ((n-1) - 1 + 1) + 1) / 2 * 2;
                    random++;
                    n-=random;
                }
            }
        }
        System.out.println(player);
    }
}


import java.io.*;
import java.util.*;
public class a279
{
    public static void main(String args[])throws IOException
    {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        String s;
        //System.out.println("Enter");
        s=in.readLine();
        StringTokenizer st=new StringTokenizer(s);
        int x,y,sum;
        x=Integer.parseInt(st.nextToken());
        y=Integer.parseInt(st.nextToken());
        if(x==0 && y==0)
        {
            System.out.println("0");
            System.exit(0);
        }
        if(x==y)
        {
            if(x>0 && y>0)
            System.out.println(Math.min(1+(x-1)*4,2+(y-1)*4));
            else if(x<0 && y<0)
            System.out.println(Math.min(3+(-x-1)*4,4+(-y-1)*4));
            System.exit(0);
        }
        else if(y==-x && y>0 && x<0)
        {
            System.out.println(Math.min(3+(-x-1)*4,2+(y-1)*4));
            System.exit(0);
        }
        else if(y==-x+1 && x>0 && y<=0)
        {
            System.out.println(Math.min(1+(x-1)*4,4+(-y-1)*4));
            System.exit(0);
        }
        else if (x>=0 && y>=0)
        {
            System.out.println(Math.max(1+(x-1)*4,2+(y-1)*4));
            System.exit(0);
        }
        else if(x<=0 && y>=0)
        {
            System.out.println(Math.max(3+(-x-1)*4,2+(y-1)*4));
            System.exit(0);
        }
        else if(x<=0 && y<=0)
        {
            System.out.println(Math.max(3+(-x-1)*4,4+(-y-1)*4));
            System.exit(0);
        }
        else if(x>=0 && y<=0)
        {
            System.out.println(Math.max(1+(x-1)*4,4+(-y-1)*4));
            System.exit(0);
        }
    }
}


import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
/*
1000000000000 1000000000002

*/
public class Main {

    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        StringTokenizer st=new StringTokenizer(br.readLine());
        long n=Long.parseLong(st.nextToken());
        long k=Long.parseLong(st.nextToken());
        if(n+n-1>=k){
            if(k<=n){
                long start = 1;
                long end = k-1;
                long ans = (end - start + 1) / 2;
                if ((end - start + 1) % 2 == 1) {
                    ans++;
                }
                if(k%2==0){
                    if ((end - start + 1) % 2 == 1) {
                        ans--;
                    }
                }
                pw.println(ans);
            }else {
                long start = k - n;
                long end = n;
                long ans = (end - start + 1) / 2;
                if ((end - start + 1) % 2 == 1) {
                    ans++;
                }
                if(k%2==0){
                    if ((end - start + 1) % 2 == 1) {
                        ans--;
                    }
                }
                pw.println(ans);
            }
        }else {
            pw.println("0");
        }

        pw.close();
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner();
        PrintWriter pw = new PrintWriter(System.out);
        rect rect1 = new rect(sc.nextLong(), sc.nextLong(), sc.nextLong(), sc.nextLong());
        rect rect2 = new rect(sc.nextLong(), sc.nextLong(), sc.nextLong(), sc.nextLong());
        rect rect3 = new rect(sc.nextLong(), sc.nextLong(), sc.nextLong(), sc.nextLong());
        long s1 = s(rect1, rect2);
        long s2 = s(rect1, rect3);
        long s3 = sAll(rect1, rect2, rect3);
        if(s1 + s2 - s3 == s(rect1))
            pw.print("NO");
        else
            pw.print("YES");
        pw.close();
    }

    public static long s(rect rect) {
        return (rect.x2 - rect.x1) * (rect.y2 - rect.y1);
    }

    public static long s(rect rect1, rect rect2) {
        if (max(rect1.x1, rect2.x1) >= min(rect1.x2, rect2.x2) || max(rect1.y1, rect2.y1) >= min(rect1.y2, rect2.y2))
            return 0;
        return (max(rect1.x1, rect2.x1) - min(rect1.x2, rect2.x2)) * (max(rect1.y1, rect2.y1) - min(rect1.y2, rect2.y2));
    }

    public static long sAll(rect rect1, rect rect2, rect rect3) {
        if (max(rect1.x1, max(rect2.x1, rect3.x1)) >= min(rect1.x2, min(rect2.x2, rect3.x2)) || max(rect1.y1, max(rect2.y1, rect3.y1)) >= min(rect1.y2, min(rect2.y2, rect3.y2)))
            return 0;
        return (max(rect1.x1, max(rect2.x1, rect3.x1)) - min(rect1.x2, min(rect2.x2, rect3.x2))) * (max(rect1.y1, max(rect2.y1, rect3.y1)) - min(rect1.y2, min(rect2.y2, rect3.y2)));
    }
}

class rect {
    long x1, y1, x2, y2;

    public rect(long x1, long y1, long x2, long y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }
}

class Scanner {
    BufferedReader br;
    StringTokenizer st = new StringTokenizer("");

    public Scanner() throws FileNotFoundException {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public String next() throws IOException {
        while (!st.hasMoreTokens())
            st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    public int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    public double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    public long nextLong() throws IOException {
        return Long.parseLong(next());
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        char[] c1 = scan.nextLine().trim().toCharArray();
        char[] c2 = scan.nextLine().trim().toCharArray();
        char[] virus = scan.nextLine().trim().toCharArray();
        int n1 = c1.length;
        int n2 = c2.length;
        int m = virus.length;
        int[][][] dp = new int[n1 + 1][n2 + 1][m + 1];
        int[][][] step = new int[n1 + 1][n2 + 1][m + 1];

        // preprocessor
        int[] next = new int[m + 1];
        next[0] = -1;
        next[1] = 0;
        int pos = 2;
        int pre = 0;
        while (pos < m) {
            if (virus[pos - 1] == virus[pre]) {
                pre++;
                next[pos] = pre;
                pos++;
            } else if (pre > 0) {
                pre = next[pre];
            } else {
                next[pos] = 0;
                pos++;
            }
        }

        for (int i = 1; i <= n1; i++) {
            for (int j = 1; j <= n2; j++) {
                for (int k = 0; k < m; k++) {
                    if (c1[i - 1] == c2[j - 1]) {
                        int kk = k;
                        while (kk >= 0 && c1[i - 1] != virus[kk]) {
                            kk = next[kk];
                        }
                        if (dp[i][j][kk + 1] < 1 + dp[i - 1][j - 1][k]) {
                            dp[i][j][kk + 1] = 1 + dp[i - 1][j - 1][k];
                            step[i][j][kk + 1] = 100 + k;
                        }
                    }

                    if (dp[i][j][k] < dp[i - 1][j][k]) {
                        dp[i][j][k] = dp[i - 1][j][k];
                        step[i][j][k] = -1;
                    }
                    if (dp[i][j][k] < dp[i][j - 1][k]) {
                        dp[i][j][k] = dp[i][j - 1][k];
                        step[i][j][k] = 1;
                    }
                }
            }
        }

        int result = 0;
        int maxK = 0;
        for (int i = 0; i < m; i++) {
            if (result < dp[n1][n2][i]) {
                result = dp[n1][n2][i];
                maxK = i;
            }
        }
        //System.out.println(result + ", " + maxK);
        if (result == 0) {
            System.out.println(result);
        } else {
            char[] cc = new char[result];
            int ccIdx = result - 1;
            int n1Idx = n1;
            int n2Idx = n2;
            int mIdx = maxK;
            while (ccIdx >= 0) {
                switch (step[n1Idx][n2Idx][mIdx]) {
                case -1:
                    n1Idx--;
                    break;
                case -2:
                    n1Idx--;
                    n2Idx--;
                    break;
                case 1:
                    n2Idx--;
                    break;
                case 0:
                    cc[ccIdx--] = c1[n1Idx - 1];
                    n1Idx--;
                    n2Idx--;
                    mIdx--;
                    break;
                default:
                    cc[ccIdx--] = c1[n1Idx - 1];
                    mIdx = step[n1Idx][n2Idx][mIdx] - 100;
                    n1Idx--;
                    n2Idx--;
                    break;
                }
            }
            System.out.println(cc);
        }
    }
}


import java.io.*;
import java.util.*;

public class D {

    final static long MOD = 1000000007;

    void solve() throws IOException {
        in("__std"); out("__std");

        int n = readInt();
        int k = 0;
        for (int i = 0; i < n; ++i) {
            if (readInt() == 2) ++k;
        }
        long a = 1;
        long b = 1;
        for (int i = 2; i <= n - k; ++i) {
            long c = a * i % MOD;
            a = (a + b) % MOD;
            b = c;
        }
        for (int i = 0; i < k; ++i) {
            a = a * (n - i) % MOD;
        }
        println(a);

        exit();
    }

    void in(String name) throws IOException {
        if (name.equals("__std")) {
            in = new BufferedReader(new InputStreamReader(System.in));
        } else {
            in = new BufferedReader(new FileReader(name));
        }
    }

    void out(String name) throws IOException {
        if (name.equals("__std")) {
            out = new PrintWriter(System.out);
        } else {
            out = new PrintWriter(name);
        }
    }

    void exit() {
        out.close();
        System.exit(0);
    }

    char readChar() throws IOException {
        return (char) in.read();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readToken());
    }

    long readLong() throws IOException {
        return Long.parseLong(readToken());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readToken());
    }

    String readLine() throws IOException {
        st = null;
        return in.readLine();
    }

    String readToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    boolean eof() throws IOException {
        return !in.ready();
    }

    void print(String format, Object ... args) {
        out.print(new Formatter(Locale.US).format(format, args));
    }

    void println(String format, Object ... args) {
        out.println(new Formatter(Locale.US).format(format, args));
    }

    void print(Object value) {
        out.print(value);
    }

    void println(Object value) {
        out.println(value);
    }

    void println() {
        out.println();
    }

    StringTokenizer st;

    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws IOException {
        new D().solve();
    }
}


import java.util.*;

public class IP {
	public static void main(String[] Args) {
		Scanner in = new Scanner(System.in);
		int min = 10000, k = 0;
		for (; k < 4; k++)
			min = Math.min(min, in.nextInt());
		int a = in.nextInt(), b = Math.min(min - 1, in.nextInt()) + 1;
		System.out.print(Math.max(b - a, 0));
	}
}


import java.util.Scanner;
/**
 * @author Eduardo Osorio
 * A01334501
 */
public class Unimodal_Array {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		String r = "YES";
		boolean c1 = true, c2 = true, c3 = true;

		int a[] = new int [n];

		for (int i=0;i<n;i++) {

			a[i] = sc.nextInt();

		}

		for (int i=0;i<n-1;i++) {
			if (c3 == true &&  a[i] > a[i+1]){

				c1 = false;
				c2 = false;

			} else if (c2 == true &&  a[i] == a[i+1]){

				r = "YES";
				c1 = false;
				c3 = true;

			} else if (c1 == true && a[i] < a[i+1]){

				c3 = true;

			} else {

				r = "NO";
				c1 = false;
				c2 = false;
				c3 = false;

			}
		}

		System.out.println(r);

		sc.close();
	}
}


import java.util.*;
public class hello
{
    public static void main(String []args)
    {
       Scanner sc=new Scanner(System.in);
       int x=sc.nextInt();
       int y=sc.nextInt();
       int z=sc.nextInt();

       if(x>y)
       {
    	   if(x-y-z>0)
    	   {
    		   System.out.println("+");
    	   }
    	   else
    	   {
    		   if(x-y==0&&z==0)
    		   {
    			   System.out.println("0");
    		   }
    		   else
    		   {
    		   System.out.println("?");
    		   }
    	   }
       }
       else
       {
    	   if(y-x-z>0)
    	   {
    		   System.out.println("-");
    	   }
    	   else
    	   {
    		   if(y-x==0&&z==0)
    		   {
    			   System.out.println("0");
    		   }
    		   else
    		   {
    		   System.out.println("?");
    		   }
    	   }
       }

    }
}


import java.util.*;
import java.io.*;
import java.text.*;
//Solution Credits: Taranpreet Singh
public class Main{
    //SOLUTION BEGIN
    //Code not meant for understanding, proceed with caution, You have been warned.
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int m = ni();
        long inv = pow(m, mod-2);
        long ans = inv;
        long[] e= new long[m+1];
        for(int i = m; i>= 2; i--){
            long y = m/i;
            e[i] = mul(new long[]{y, 2*m-y, pow(m-y,mod-2),pow(m,mod-2)});
            for(int j = i*2; j<= m; j+=i)e[i] = (e[i]+mod-e[j])%mod;
            ans+=e[i];
            if(ans>=mod)ans-=mod;
        }
        pn(ans);
    }
    long mul(long[] a){
        long ans= 1;
        for(long x:a)ans = (ans*x)%mod;return ans;
    }
    long pow(long a, long p){
        long o = 1;
        while(p>0){
            if(p%2==1)o = (a*o)%mod;
            a = (a*a)%mod;
            p>>=1;
        }
        return o;
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)1e9+7, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)1e5+7;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        int T = (multipleTC)?ni():1;
        //Solution Credits: Taranpreet Singh
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

    class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws Exception{
            br = new BufferedReader(new FileReader(s));
        }

        String next() throws Exception{
            while (st == null || !st.hasMoreElements()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (IOException  e){
                    throw new Exception(e.toString());
                }
            }
            return st.nextToken();
        }

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}


import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main {

    public static BufferedReader in;
    public static StringTokenizer tok = new StringTokenizer("");

    public static String readLine() { // читает строку до самого конца
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String readString() { // читает строку до пробела/табуляции/перевода строки

        while (!tok.hasMoreTokens()) {
            String line = readLine();
            if (null == line) return null; // ввода больше нет
            tok = new StringTokenizer(line); // сюда можно передать вторым параметром строку с символами, по которым надо отсекать, по умолчанию это пробел и табуляция
        }

        return tok.nextToken();
    }

    public static int readInt() { // аналогично для readLong(), readDouble(), ...
        return Integer.parseInt(readString());
    }

    public static void main(String[] args){
        in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int n = readInt();
        int k = readInt();
        int m = readInt();
        int a = readInt();

        //ArrayList<Candidate> candidates = new ArrayList<>();
        Candidate[] candidates = new Candidate[n];
        for (int i = 0; i < n; i++) {
            candidates[i]  = new Candidate(i,0,0,1);
        }
        for (int i = 0; i < a; i++) {
            int l = readInt()-1;
            candidates[l].vote(i);
        }
        Arrays.sort(candidates);

        int minFor2 = candidates[k-1].votes;

        for (int i = k; i < n; i++) {
            if(candidates[i].votes + (m-a) > minFor2)
                candidates[i].type = 2;
            else
                candidates[i].type = 3;
        }

        if(n > k) {
            for (int i = 0; i < k; i++) {
                int ndVotes = candidates[i].votes + 1;
                int votes = 0;
                for (int j = i + 1; j < k + 1; j++) {
                    votes +=ndVotes - candidates[j].votes;
                }
                if (votes <= m - a)
                    candidates[i].type = 2;
            }
        }

        if(m-a > 0)
        {
            for (int i = 0; i < k; i++) {
                if(candidates[i].votes == 0) candidates[i].type = 2;
            }
        }
        else {
            for (int i = 0; i < k; i++) {
                if (candidates[i].votes == 0) candidates[i].type = 3;
            }
        }

        int[] ans = new int[n];

        for (int i = 0; i < n; i++) {
            ans[candidates[i].id] = candidates[i].type;
        }

        for (int i = 0; i < n; i++) {
            out.print(ans[i]+" ");
        }

        out.flush();
        out.close();
    }

    static class Candidate implements Comparable<Candidate>{
        public int id;
        public int votes;
        public int lastT;
        public int type;

        public Candidate(int id,int votes,int lastT,int type)
        {
            this.id = id;
            this.votes = votes;
            this.lastT = lastT;
            this.type = type;
        }

        public void vote(int lastT)
        {
            votes++;
            this.lastT = lastT;
        }

        public int compareTo(Candidate p){
            if(p.votes > this.votes)
                return 1;
            else if(p.votes == this.votes)
                return p.lastT < this.lastT?1:-1;
            else return -1;
        }
    }
}


import java.util.*;

public class LearnFromMaths
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        int b=sc.nextInt();
        int c=sc.nextInt();
        long arr[]=new long[1000000];
        int k=0;
        long x=0;
        long ans=0;
        for(int i=1;i<=81;i++)
        {
            x=b*(long)Math.pow(i,a)+c;
            if(x<1e9  && x>0 && sum(x,i))
            {
                ans++;
                arr[k++]=x;
            }
        }
        System.out.println(ans);
        for(int i=0;i<k;i++)

        {
            System.out.print(arr[i]+" ");
        }
    }
    public static boolean sum(long y,int i){
        long sum = 0;
        for (sum = 0; y > 0; sum += y % 10,y/= 10);
        return sum==i;
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long n = in.nextLong();
            long m = in.nextLong();
            ModuloArithmetic moduloArithmetic = new ModuloArithmetic(998244353L);

            long factm = moduloArithmetic.factorial(m);
            long fact1 = moduloArithmetic.factorial(m - (n - 1));
            long fact2 = moduloArithmetic.factorial(n - 1);
            long pow2 = n >= 3 ? moduloArithmetic.powmod(2, n - 3) : 1;
            long t = moduloArithmetic.mul(fact1, fact2);
            long ans = moduloArithmetic.div(factm, t);
            ans = moduloArithmetic.mul(ans, n - 2);
            ans = moduloArithmetic.mul(ans, pow2);
            out.println(ans);
        }

    }

    static class InputReader {
        final InputStream is;
        final byte[] buffer = new byte[1024];
        int curCharIdx;
        int nChars;

        public InputReader(InputStream is) {
            this.is = is;
        }

        public int read() {
            if (curCharIdx >= nChars) {
                try {
                    curCharIdx = 0;
                    nChars = is.read(buffer);
                    if (nChars == -1)
                        return -1;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return buffer[curCharIdx++];
        }

        public long nextLong() {
            int sign = 1;
            int c = skipDelims();
            if (c == '-') {
                sign = -1;
                c = read();
                if (isDelim(c))
                    throw new RuntimeException("Incorrect format");
            }
            long val = 0;
            while (c != -1 && !isDelim(c)) {
                if (!isDigit(c))
                    throw new RuntimeException("Incorrect format");
                val = 10L * val + (c - '0');
                c = read();
            }
            return val * sign;
        }

        private final int skipDelims() {
            int c = read();
            while (isDelim(c)) {
                c = read();
            }
            return c;
        }

        private static boolean isDelim(final int c) {
            return c == ' ' ||
                    c == '\n' ||
                    c == '\t' ||
                    c == '\r' ||
                    c == '\f';
        }

        private static boolean isDigit(final int c) {
            return '0' <= c && c <= '9';
        }

    }

    static class Algorithms {
        public static long powmod(long a, long n, long mod) {
            long res = 1;
            while (n != 0) {
                if ((n & 1) == 1)
                    res = (res * a) % mod;
                a = (a * a) % mod;
                n >>= 1;
            }
            return res;
        }

        public static long inverseByModulo(long a, long n) {
            long t = 0, newt = 1, r = n, newr = a;
            while (newr != 0) {
                long q = r / newr;

                long temp = newt;
                newt = t - q * newt;
                t = temp;

                temp = newr;
                newr = r - q * newr;
                r = temp;
            }

            if (r > 1)
                return 0;
            if (t < 0)
                t += n;
            return t;
        }

    }

    static class ModuloArithmetic {
        final long MODULO;

        public ModuloArithmetic(long mod) {
            this.MODULO = mod;
        }

        public long mul(long a, long b) {
            return (a * b) % MODULO;
        }

        public long div(long a, long b) {
            return (a * Algorithms.inverseByModulo(b, MODULO)) % MODULO;
        }

        public long factorial(long n) {
            long ans = 1;
            for (int i = 2; i <= n; i++) ans = mul(ans, i);
            return ans;
        }

        public long powmod(long k, long n) {
            return Algorithms.powmod(k, n, MODULO);
        }

    }
}


import java.io.*;
import java.util.*;

public class Main {
   public static void main(String[] args) throws FileNotFoundException
   {
	   (new Main()).solve();
   }
   public void Main() {
   }

   void solve()  throws FileNotFoundException {
      Scanner in = new Scanner(System.in);
	  PrintWriter out = new PrintWriter(System.out);
     // Scanner in = new Scanner(new FileReader("input.txt"));
	//  PrintWriter out = new PrintWriter("output.txt");
	  String s = in.next();
	  ArrayList<Integer> a = new ArrayList<Integer>();
	  int prevh = -1;
	  int prevm = -1;
	  boolean flag = true;

	  for (int j = 2; j < 100; j++) {
		  int h = 0;
		  int m = 0;
		  for (int i = 0; i < s.indexOf(':'); i++) {
			  int t = (int) s.charAt(i) - (int)'0';
			  if (t >=0 && t <= 9) {

			  } else {
				  t = (int) s.charAt(i) - (int)'A' + 10;
			  }
			  if (t >= j) {
				  h = -1;
				  break;
			  }
			  h = h * j + t;
		  }
		  for (int i = s.indexOf(':') + 1; i < s.length(); i++) {
			  int t = (int) s.charAt(i) - (int)'0';
			  if (t >=0 && t <= 9) {

			  } else {
				  t = (int) s.charAt(i) - (int)'A' + 10;
			  }
			  if (t >= j) {
				  m = -1;
				  break;
			  }
			  m = m * j + t;
		  }
		  if (h >= 0 && h <= 23 && m >= 0 && m <= 59) {
			  a.add(j);
			  if (h == prevh && m == prevm) {
				  flag = false;
				  break;
			  }
		  }
				  prevh = h;
				  prevm = m;

	  }

	  if (flag) {
		  if (a.size() == 0) {
			  out.print(0);
		  }
		  for (Integer t : a) {
			  out.print(t + " ");
		  }
	  } else {
		  out.print(-1);
	  }

	  out.close();
   }

};


import java.util.HashMap;
import java.util.Scanner;

public class CODE_OBSTUFICATIION {

	public static void main(String[] args) {

		Scanner nik = new Scanner(System.in);
		String s = nik.next();
		boolean b = true;
		HashMap<Character, Integer> hm = new HashMap<>();
		for (int i = 0; i < s.length(); i++) {
			int temp = s.charAt(i) - 'a';
			if (hm.size() < temp) {
				b = false;
				break;
			} else {
				hm.put(s.charAt(i), hm.getOrDefault(s.charAt(i) + 1, 0));
			}

		}

		System.out.println(b == true ? "YES" : "NO");

	}

}