import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

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

    static class Task {
    	public static final long Mod=(long) (1e9+7);

        public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException {
        	int h=sc.nextInt();
        	int w=sc.nextInt();
            int[] col=new int[w+1];     //每列最起码的高
            int[] row=new int[h+1];     //每列最起码的宽
            boolean[][] vis=new boolean[h+1][w+1];

            Arrays.fill(vis[0], true);
            for(int i=1;i<=h;i++) {
            	row[i]=sc.nextInt()+1;
                for(int j=0;j<=row[i]-1;j++)
                	vis[i][j]=true;
            }
            for(int i=1;i<=w;i++) {
            	col[i]=sc.nextInt()+1;
            	for(int j=1;j<=col[i]-1;j++) {
            		if((vis[j][i-1]&&!vis[j][i])||(vis[j-1][i]&&!vis[j][i])) {
            			out.println("0");
            			return ;
            		}
            	}
            }
            for(int i=1;i<=h;i++)
            	for(int j=1;j<=w;j++)
            		vis[i][j]=false;
            for(int i=1;i<=w;i++) {
            	for(int j=1;j<=col[i]-1;j++) {
            		vis[j][i]=true;
            	}
            }
            for(int i=1;i<=h;i++) {
                for(int j=1;j<=row[i]-1;j++)
                	if((vis[i-1][j]&&!vis[i][j])||(vis[i][j-1]&&!vis[i][j])) {
                		out.println("0");
                		return ;
                	}
            }

            long ans=1;

            for(int i=1;i<=h;i++) {
            	for(int j=1;j<=w;j++) {

            		if(i>col[j]&&col[j]<=h&&j>row[i]&&row[i]<=w) {
            			ans=(ans*2)%Mod;
            		}
            	}
            }
            out.println(ans);
        }

    }

    static class InputReader{
        StreamTokenizer tokenizer;
        public InputReader(InputStream stream){
            tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream)));
            tokenizer.ordinaryChars(33,126);
            tokenizer.wordChars(33,126);
        }
        public String next() throws IOException {
            tokenizer.nextToken();
            return tokenizer.sval;
        }
        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }
        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }
        public boolean hasNext() throws IOException {
            int res=tokenizer.nextToken();
            tokenizer.pushBack();
            return res!=tokenizer.TT_EOF;
        }

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

        public BigInteger nextBigInteger() throws IOException {
        	return new BigInteger(next());
        }
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt(),m=sc.nextInt(),s=sc.nextInt();
          n--;
            m--;
            long positions;
            if( s > n )
                positions = n+1;
            else
                positions = n%s+1;
            if( s > m )
                positions *= m+1;
            else
                positions *= (m%s+1);

            long dxy = (n/s+1)*(m/s+1);

            System.out.println(positions*dxy);

    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class C {

    static long solve(long l) {
        if(l==0) {
            return 0;
        } else if(l==1) {
            return 1;
        }
        StringBuilder s=new StringBuilder(); s.append("1");
        while(Long.parseLong(s.toString())<l) {
            s.append("1");
        }

        long l1=Math.abs(Long.parseLong(s.toString().substring(0, s.length()-1))-l);
        long l2=Math.abs(Long.parseLong(s.toString())-l);
        long ret=solve(l1)+s.length()-1;
        if(l2<l) {
            ret=Math.min(ret, solve(l2)+s.length());
        }
        return ret;
    }

    static StringBuilder sb=new StringBuilder();
    static void parse(String l, int[] here) {
        sb.setLength(0);
        int len=l.length(), j=0;
        for (int i=0; i<len; i++) {
            char c=l.charAt(i);
            if(c==' ') {
                here[j++]=Integer.parseInt(sb.toString());
                sb.setLength(0);
            } else {
                sb.append(c);
            }
        }
        if(sb.length()>0) {
            here[j++]=Integer.parseInt(sb.toString());
        }
    }

    static void run_stream(InputStream ins) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        long n=Long.parseLong(br.readLine());
        System.out.println(solve(n));
    }

    public static void main(String[] args) throws IOException {
        run_stream(System.in);
    }

}


import	java.util.*;
public	class	Main{
	public	static	void	main(String[]args){
		Scanner	cin=new	Scanner(System.in);
		long	s=0,n=cin.nextLong(),m,x=2,y,z,a,b,c;
		if(0==n%6)	for(n/=3;x*x*x<=n;++x)
			if(1>n%x)	for(m=n/x,y=x;y*y<=m;++y)
				if(1>m%y&&1>(1&(x^(z=m/y)^y))&&1<(a=x+y-z))
					s+=(c=(y<<1)-a)==a?1:(b=(x<<1)-a)==a||b==c?3:6;
		System.out.print(s);
	}
}


import java.io.*;
public class LimakAndRadewoosh
{
public static void main(String[] args)
{
String Pobeda = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
StringBuffer o = new StringBuffer(br.readLine());
StringBuffer s1 = new StringBuffer(br.readLine());
StringBuffer s2 = new StringBuffer(s1.substring(0,s1.length()));
StringBuffer t = new StringBuffer(br.readLine());
StringBuffer t2 = new StrigBffer(t.substring(0,t.length()));
int count = Integer.parseInt(o.substring(0,o.indexOf(" ")));
int c = Integer.parseInt(o.substring(s1.indexOf(" ") + 1,o.length()));
int[] timeLimak = new int[count];
int[] timeRadewoosh = new int[count];
int[] zadachaLimak = new int[count];
int[] zadachaRadewoosh = new int[count];
int[] resLimak = new int[count];
int[] resRadewoosh = new int[count];
int itogLimak = 0;
int itogRadewoosh = 0;
for(int i = 0; i < count;i++)
{
 zadachaLimak[i] = Integer.parseInt(s1.substring(0,s1.indexOf(" ")));
 s1.delete(0,s1.indexOf(" "));
 timeLimak[i] = Integer.parseInt(t.substring(0,t.indexOf(" ")));
 t.delete(0,t.indexOf(" "));

}
for(int i = count;i >= 0;i--)
{
      zadachaRadewoosh[i] = Integer.parseInt(s2.substring(s2.lastIndexOf(" "),s2.length()));
      s2.delete(s2.lastIndexOf(" "),s2.length());
      timeRadewoosh[i] = Integer.parseInt(t2.substring(t2.lastIndexOf(" "),t2.length()));
      t2.delete(t2.lastIndexOf(" "),t2.length());
}
for(int i = 0;i < count;i++)
{
 resLimak[i] = zadachaLimak[i] - (c * timeLimak[i]);
}
for(int i = count;i >= 0;i--)
{
      resRadewoosh[i] = zadachaRadewoosh[i] - (c * timeRadewoosh[i]);
}
for(int u = 0,p = count;u < count && p >= 0;u++,p--)
{
      itogLimak += resLimak[u];
      itogRadewoosh += resRadewoosh[p];
}
if(itogLimak > itogRadewoosh)
{
 Pobeda = "Limak";
}
else if(itogRadewoosh > itogLimak)
{
 Pobeda = "Radewoosh";
}
else if(itogLimak == itogRadewoosh)
{
      Pobeda = "Tie";
}
}
catch(Exception excp)
{

}
finally
{
      System.out.println(Pobeda);
}
}
}


public class Main {

    public static void main(String[] args) {
	    Scanner in = new Scanner(System.in);
        double d = in.nextDouble();
        double L = in.nextDouble();
        double v1 = in.nextDouble();
        double v2 = in.nextDouble();

        double x = (L - d) * v1/ (v1 + v2);
        System.out.print(x/v1);
    }
}


import java.io.*;
public class A
{
public static void main(String[] args)
{
      int day = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
String s = br.readLine();
int aS = Integer.parseInt(s.substring(0,2));
int bS = Integer.parseInt(s.substring(s.length() - 2));
String s1 = br.readLine();
int a = Integer.parseInt(s1.substring(0,1));
int b = Integer.parseInt(s1.substring(s1.length() - 1));
int tGusSt = 10;
int tGusEnd = 22;
int tBoyEnd = 14;
int tCount = 10;
do
{
 tCount++;
 if(tCount == tBoyEnd)
 {
       isUp  = false;
       day++;
       aS += a;
       if(tCount != tGusEnd)
       {
             aS += a;
             aS -= b;
       }
 }
 else
 {
       isUp = true;
 }
 if(isUp == true)
 {
       if(tCount != tBoyEnd)
       {
             aS += b;
       }
 }
}while(aS != bS);
}
catch(Exception excp)
{

}
finally
{
      System.out.println(day);
}
}
}


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

public class Permutation {

	static HashSet<String> perm;
	static int n,k;

	static String toString(int[] idx) {
		StringBuilder sb = new StringBuilder("");
		for(int i=0;i<k;i++)
			sb.append(""+idx[i]);
		return sb.toString();

	}

	static void permutations(int[] idx,int i) {
		if(!perm.contains(toString(idx))) perm.add(toString(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(int idx[],int a, int b) {
		int remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new TreeSet<>();
        int idx[] = new int[k];
        for(int i=1;i<=k;i++) idx[i-1] = i;
        for(int i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(int i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = Math.min(min, x);
        		max = Math.max(max, x);
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

		String next() {
			while(!st.hasMoreTokens())
				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());
		}

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

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

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}


public class C {

	public C () {
		String YES = "Polycarp", NO = "Vasiliy";

		int [] A = sc.nextInt(2), B = sc.nextInt(2);

		for (;;) {
			if (!canMove(A, B, 1, 0))
				move(A, B, 0, 1);
			else if (!canMove(A, B, 0, 1))
				move(A, B, 1, 0);
			else if (A[0] > B[0])
				move(A, B, 1, 0);
			else
				move(A, B, 0, 1);

			if (A[0] <= B[0] && A[1] <= B[1])
				exit(YES);

			if (canMove(B, A, 1, 1))
				move(B, A, 1, 1);
			else if (canMove(B, A, 1, 0))
				move(B, A, 1, 0);
			else
				move(B, A, 0, 1);

			if (B[0] == 0 && B[1] == 0)
				exit(NO);
		}
	}

	void move(int [] A, int [] B, int x, int y) {
		if (canMove(A, B, x, y)) {
			A[0] -= x;
			A[1] -= y;
		}
	}

	boolean canMove(int [] A, int [] B, int x, int y) {
		if (A[0] - x == B[0] && A[1] - y == B[1])
			return false;
		else if (A[0] - x < 0 || A[1] - y < 0)
			return false;
		else
			return true;
	}

	////////////////////////////////////////////////////////////////////////////////////
	private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
	private static class IOUtils {
		public static class MyScanner {
			public String next() { newLine(); return line[index++]; }
			public int nextInt() { return Integer.parseInt(next()); }
			public int [] nextInt (int N) {
				int [] res = new int [N];
				for (int i = 0; i < N; ++i)
					res[i] = nextInt();
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol() { return index == line.length; }
			private String readLine() {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine() {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim(String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static void start() { if (t == 0) t = millis(); }
		private static void append(StringBuilder b, Object o, String delim) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					append(b, java.lang.reflect.Array.get(o, i), delim);
			} else if (o instanceof Iterable<?>)
				for (Object p : (Iterable<?>) o)
					append(b, p, delim);
			else {
				if (o instanceof Double)
					o = new java.text.DecimalFormat("#.############").format(o);
				b.append(delim).append(o);
			}
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
		private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
		private static void exit() {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(IOUtils.time());
			System.exit(0);
		}
		private static long t;
		private static long millis() { return System.currentTimeMillis(); }
		private static String time() { return "Time: " + (millis() - t) / 1000.0; }
	}
	public static void main (String[] args) { new C(); IOUtils.exit(); }
}


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.PortUnreachableException;
import java.util.*;

// written by luchy0120

public class Main {
    public static void main(String[] args) throws Exception {

        new Main().run();
    }

    static int groups = 0;
    static int[] fa;
    static int[] sz;

    static void init(int n) {
        groups = n;
        fa = new int[n];
        for (int i = 1; i < n; ++i) {
            fa[i] = i;
        }
        sz = new int[n];
        Arrays.fill(sz, 1);
    }

    static int root(int p) {
        while (p != fa[p]) {
            fa[p] = fa[fa[p]];
            p = fa[p];
        }
        return p;
    }

    static void combine(int p, int q) {
        int i = root(p);
        int j = root(q);
        if (i == j) {
            return;
        }
        if (sz[i] < sz[j]) {
            fa[i] = j;
            sz[j] += sz[i];
        } else {
            fa[j] = i;
            sz[i] += sz[j];
        }
        groups--;
    }

    int child[];
    int color[],dfn[],low[],stack[],cnt[];
    boolean vis[];
    boolean iscut[];
    int deep,top,n,m,sum,ans;
    List<Integer> g[];
    int root = 0;
    //  无向图的强连通分量
    void tarjanNonDirect(int u1) {

        int stk[] = new int[10001];
        int fatk[] = new int[10001];
        int p = 0;
        stk[p] = u1;
        fatk[p] = -1;
        p= 1;
        ot: while(p>0) {
            int u  = stk[p-1];
            int fa = fatk[p-1];

            if(dfn[u]==0) {
                low[u] = dfn[u] = ++deep;
            }
            // stack[top++] = u;

            for (; h[u] != -1; h[u] = ne[h[u]]) {
                int v = to[h[u]];
                if (dfn[v] == 0) {
                    //tarjanNonDirect(v);

                    fatk[p] = u;
                    stk[p++] = v;
                    continue ot;
                } else {
                    low[u] = Math.min(low[u], dfn[v]);
                    // 没有特判是否直接指向父亲
                    // 回边，使用dfn【v】更新low【u】,因为可能是指向父亲，而父亲的low可能比较小
                }
            }
            --p;

            if (fa != -1) {
                low[fa] = Math.min(low[fa], low[u]);
                if (low[u] >= dfn[fa]) {
                    if (fa != root || ++child[fa] > 1) {     // 不是root，直接记为cut，是root，判断是否有两个儿子
                        iscut[fa] = true;
                    }
                    ++dcc_cnt;
                    // 一个割点可能会被多个点双共享
                    //  int z = -1;
                    //    do {
                    //        z = stack[--top];
                    //      dcc[dcc_cnt].add(z);
                    //    } while(z != v);
                    //   dcc[dcc_cnt].add(u);
                }

            }

        }
    }
    int gd = 0;
    int id =-1;
    int scc_cnt = 0;
    int sccno[];
    // 有向图的强连通分量
    void tarjan(int u) {
        int stk[] = new int[10001];
        //   int tptk[] = new int[10001];

        //  int fatk[] = new int[10001];
        int p  =1; stk[0] = u;//fatk[0] =-1;
        ot:while(p>0) {
            u  = stk[p-1];
            //  int fa  = fatk[p-1];
            if (dfn[u] == 0) {
                low[u] = dfn[u] = ++deep;
                stack[top++] = u;

            }

            for (; hc[u] != -1; hc[u] = ne[hc[u]]) {
                int v = to[hc[u]];
                if (dfn[v] == 0) {
                    stk[p++] = v;
                    continue ot;
                    //  low[u] = Math.min(low[u], low[v]);
                } else if (sccno[v] == 0) {
                    // dfn>0 but sccno==0, means it's in current stack
                    low[u] = Math.min(low[u], low[v]);
                }
            }

            p--;
            if (dfn[u] == low[u]) {
                sccno[u] = ++scc_cnt;
                if(u==1){
                    id = scc_cnt;
                }

                while (stack[top - 1] != u) {
                    sccno[stack[top - 1]] = scc_cnt;
                    if(stack[top - 1]==1){
                        id = scc_cnt;
                    }
                    --top;
                }

                --top;
            }
            if(p>=1){
                int fa = stk[p-1];
                low[fa] = Math.min(low[fa], low[u]);
            }
        }
    }
    int rr =0;
//    void solve() {
//
//    }

//    int get_room(int i,int j){
//        return i/3*3 + j/3;
//    }

//    int a[][] = new int[9][9];
//    int space = 0;
//
//    boolean vis_row[][] = new boolean[9][10];
//    boolean vis_col[][] = new boolean[9][10];
//    boolean vis_room[][] = new boolean[9][10];
//    int val[][][] =new int[9][9][];
//    int prepare[][];
//
//    void dfs(int rt){
//
//    }

    int h[],to[],ne[];int ct =0;
    void add(int u,int v){
        // u--;v--;
        to[ct] = v;
        ne[ct] = h[u];
        h[u] = ct++;

    }

    int dcc_cnt = 0;
    int time = 0;

    long summ[];
    int v[];
    int hc[];
    void solve() {
//        File f = new File("C:\\Users\\Luqi\\Desktop\\1.png");
//        BufferedImage bi = null;
//        try {
//            bi = ImageIO.read(f);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        int width = bi.getWidth();
//        int height = bi.getHeight();
        String ele[] = {"H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og"};

        String me[] = new String[ele.length];
        for(int i=0;i<ele.length;++i){
            me[i] = ele[i].toUpperCase();
        }
        String s =ns();

        boolean dp[] = new boolean[s.length()];dp[0] =true;
        for(int j=1;j<=s.length();++j){
            for(String m:me) {
                if (j >= 2 && dp[j - 2] && s.substring(j - 2, j).equals(m)){
                    dp[j]  = true;
                }
                if (j >= 1 && dp[j - 1] && s.substring(j - 1, j).equals(m)){
                    dp[j]  = true;
                }
            }
        }
        println(dp[s.length()]?"YES":"NO");

      //  println(width);
//      //  println(height);
//        int i  =ni();
//        int j  =ni();

//        for(int i=0;i<height;++i){
//            for(int j=0;j<width;++j){
//               int me =  bi.getRGB(i,j);
//               print(me==-1?0:1);
//            }
//            println();
//        }

//        int minx = bi.getMinX();
//        int miny = bi.getMinY();
//        System.out.println("width=" + width + ",height=" + height + ".");
//        System.out.println("minx=" + minx + ",miniy=" + miny + ".");
//        int b[][][] = new int[64][64][3];
//
//        for (int i = minx; i < width; i++) {
//            for (int j = miny; j < height; j++) {
//                int pixel = bi.getRGB(i, j);
//              //  print(pixel);
//               // b[j][i] = pixel;
//
//                b[j][i][0] = (pixel & 0xff0000) >> 16;
//                b[j][i][1] = (pixel & 0xff00) >> 8;
//                b[j][i][2] = (pixel & 0xff);
//
//            }
//            println();
//        }
//
//        for(int i=0;i<64;++i){
//            print("\"");
//            for(int j=0;j<64;++j){
//                print(b[i][j][0]<=50?"*":" ");
//            }
//            println("\",");
//        }
//        //println(b[0][0]);

//
//
//
//
//
//            }
//        }
    //    print("No");

//        int n = ni();
//        int m  = n*(n+1)/2;
//        int k = ni();
//        int p = 0;
//
//        double x[] = new double[n];
//        double y[] = new double[n];
//
//        for(int i=0;i<n;++i){
//            x[i] = nd();
//            y[i] = nd();
//        }
//
//        List<Item> li = new ArrayList<>();
//        for(int i=0;i<n;++i){
//            for(int j=i+1;j<n;++j){
//               double r =  (x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]);
//               li.add(new Item(r,i,j));
//            }
//        }
//        Collections.sort(li,(xx,yy)->Double.compare(xx.s,yy.s));
//
//        init(n + 1);
//
//        int s = 0;
//        int c = n;
//        for (int i = 0; i < li.size(); ++i) {
//            int p1 = li.get(i).a;
//            int p2 = li.get(i).b;
//            if (root(p1) != root(p2)) {
//                combine(p1, p2);
//                c--;
//                if(c==k-1){
//                    print(roundS(Math.sqrt(li.get(i).s),2));
//                    break;
//                }
//            }
//        }

    }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//    }

    static long mul(long a, long b, long p)
    {
        long res=0,base=a;
        while(b>0)
        {
            if((b&1L)>0)
                res=(res+base)%p;
            base=(base+base)%p;
            b>>=1;
        }
        return res;
    }

    static long mod_pow(long k,long n,long p){
        long res = 1L;
        long temp = (k%p+p)%p;
        while(n!=0L){
            if((n&1L)==1L){
                res = ((res*temp)%p+p)%p;
            }
            temp = ((temp * temp)%p+p)%p;
            n = n>>1L;
        }
        return res%p;
    }
    public static String roundS(double result, int scale){
        String fmt = String.format("%%.%df", scale);
        return String.format(fmt, result);
    }

//    void solve() {
//
//        for(int i=0;i<9;++i) {
//            for (int j = 0; j < 9; ++j) {
//                int v = ni();
//                a[i][j] = v;
//                if(v>0) {
//                    vis_row[i][v] = true;
//                    vis_col[j][v] = true;
//                    vis_room[get_room(i, j)][v] = true;
//                }else{
//                    space++;
//                }
//            }
//        }
//
//
//        prepare = new int[space][2];
//
//        int p = 0;
//
//        for(int i=0;i<9;++i) {
//            for (int j = 0; j < 9; ++j) {
//                if(a[i][j]==0){
//                    prepare[p][0] = i;
//                    prepare[p][1]= j;p++;
//                    List<Integer> temp =new ArrayList<>();
//                    for(int k=1;k<=9;++k){
//                        if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){
//                            temp.add(k);
//                        }
//                    }
//                    int sz = temp.size();
//                    val[i][j] = new int[sz];
//                    for(int k=0;k<sz;++k){
//                        val[i][j][k] = temp.get(k);
//                    }
//                }
//            }
//        }
//        Arrays.sort(prepare,(x,y)->{
//           return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length);
//        });
//        dfs(0);
//
//
//
//
//
//
//
//
//
//
//    }

    InputStream is;
    PrintWriter out;

    void run() throws Exception {
        //is = new FileInputStream(new File("C:\\Users\\Luqi\\Downloads\\P3387_9.in"));
        is = System.in;
        out = new PrintWriter(System.out);

        solve();
        out.flush();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private char ncc() {
        int b = readByte();
        return (char) b;
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private String nline() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!isSpaceChar(b) || b == ' ') {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[][] nm(int n, int m) {
        char[][] a = new char[n][];
        for (int i = 0; i < n; i++) a[i] = ns(m);
        return a;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private long[] nal(int n) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++) a[i] = nl();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
        }
        ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        while (true) {
            if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0');
            else return minus ? -num : num;
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
        }
        ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        while (true) {
            if (b >= '0' && b <= '9') num = num * 10 + (b - '0');
            else return minus ? -num : num;
            b = readByte();
        }
    }

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

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

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

    void printArray(int a[],int from){
        int l = a.length;
        for(int i=from;i<l;++i){
            print(a[i]);
            if(i!=l-1){
                print(" ");
            }
        }
        println();
    }

    void printArray(long a[],int from){
        int l = a.length;
        for(int i=from;i<l;++i){
            print(a[i]);
            if(i!=l-1){
                print(" ");
            }
        }
        println();
    }
}


import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);

        //System.out.println(qmod(2,5,100));

        long S[][]=new long[5005][5005];
        long mod=998244353;
        S[1][1]=1;
        S[0][0]=0;
        for(int i=1;i<=5000;i++){
            S[i][i]=1;S[i][0]=0;
        }
        for(int i=2;i<=5000;i++){
            for(int j=1;j<=i;j++){
                S[i][j]=(S[i-1][j]*j%mod+S[i-1][j-1])%mod;
            }
        }
        long n=sc.nextLong();long m=sc.nextLong();int k=sc.nextInt();
        m=qmod(m,mod-2,mod);
        long dp[]=new long[5005];dp[0]=1;
        for(int i=1;i<=Math.min(n,k);i++)dp[i]=dp[i-1]*(n-i+1)%mod;

        long ans=0;
        for(int i=1;i<=Math.min(n,k);i++){
            ans=(ans+dp[i]*qmod(m,i,mod)%mod*S[k][i]%mod)%mod;
        }
        System.out.println(ans);

    }
    public static long qmod(long a,long b,long mod){
        long ans=1;
        while(b>=1){

            if((b&1)!=0){
                ans=ans*a%mod;
            }
            a=a*a%mod;
            b=b>>1;
        }return ans;
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.stream.IntStream;

        public class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner() {
            try {
                br = new BufferedReader(new InputStreamReader(System.in));
                st = new StringTokenizer("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public String next() {
            if (st.hasMoreTokens())
                return st.nextToken();
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return st.nextToken();
        }

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

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

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

        public String nextLine() {
            String line = "";
            try {
                line = br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return line;
        }

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

        public long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }

        public char[] nextCharArray() {
            return nextLine().toCharArray();
        }
    }

public class Main
{

    private static int maxMark = 650;

    public static void main(String[] args)
    {
	FastScanner fs = new FastScanner();
        boolean[] aMarks = new boolean[maxMark + 1];
        int i = 0;
        while(i <= maxMark)
        {
            aMarks[i] = false;
            i = i + 1;
        }
        int n = fs.nextInt();
        i = 0;
        int ans = 0;
        while(i < n)
        {
            int mark = fs.nextInt();
            if(mark != 0)
            {
            if(!aMarks[mark])
            	{
                	aMarks[mark] = true;
                	ans = ans + 1;
            	}
            }
            i = i + 1;
        }
        System.out.print(ans);
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import Utils.MathUtils;

public final class Main
{
	static long mod = 998244353l;

	public static void main(String[] args) throws IOException
	{
		Scanner in = getScan(args);
		// int tt = in.nextInt();
		// while (tt-- > 0)
		// {
		int n = in.nextInt();
		int m = in.nextInt();
		long res = MathUtils.divMod(fact(m), fact(n - 1) * fact(m - n + 1), mod);

		if (n < 3)
		{
			System.out.println(0);
			return;
		}
		long pow = MathUtils.binpowMod(2, n - 3, mod);
		long tmp = (pow * (n - 2)) % mod;
		res = (res * tmp) % mod;
		System.out.println(res);
		// }
	}

	public static long fact(int n)
	{
		long res = 1;
		for (int i = 1; i <= n; i++)
		{
			res = (res * i) % mod;
		}
		return res;
	}

	public static int log2nlz(int bits)
	{
		if (bits == 0) return 0; // or throw exception
		return 31 - Integer.numberOfLeadingZeros(bits);
	}

	static Scanner getScan(String[] args) throws IOException
	{
		if (args.length == 0)
		{
			return new Scanner(System.in);
		}
		else
		{
			return new Scanner(new File(args[0]));
		}
	}

	static BufferedReader getBuffer(String[] args) throws IOException
	{
		if (args.length == 0)
		{
			return new BufferedReader(new InputStreamReader(System.in));
		}
		else
		{
			return new BufferedReader(new FileReader(args[0]));
		}
	}

}


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

public class H {
    FastScanner in;
    PrintWriter out;

    int calc(int size) {
        if (size <= 1) {
            return 0;
        }
        return size * (size - 1) / 2 + calc(size / 2) + calc((size + 1) / 2);
    }

    class Query {
        int fr, to;
        int id;

        public Query(int fr, int to, int id) {
            this.fr = fr;
            this.to = to;
            this.id = id;
        }
    }

    List<Integer> left = new ArrayList<>();
    List<Integer> right = new ArrayList<>();

    int first(int from, int to, int yFr, int yTo) {
        while (from != to + 1 && (a[from] < yFr || a[from] > yTo)) {
            from++;
        }
        return from;
    }

    int last(int from, int to, int yFr, int yTo) {
        while (to != from - 1 && (a[to] < yFr || a[to] > yTo)) {
            to--;
        }
        return to;
    }

    List<Integer> go(List<Integer> from, List<Integer> to, int yFr, int yTo) {
        for (int i : from) {
            if (i >= a.length) {
                throw new AssertionError();
            }
        }
        for (int i : to) {
            if (i >= a.length) {
                throw new AssertionError();
            }
        }
        if (from.size() == 0) {
            return new ArrayList<>();
        }
        if (yFr == yTo) {
            List<Integer> res = new ArrayList<>();
            for (int i = 0; i < from.size(); i++) {
                res.add(from.get(i));
            }
            return res;
        } else {
            int yMid = (yFr + yTo) / 2;
            List<Integer> join1 = new ArrayList<>();
            List<Integer> join2 = new ArrayList<>();
            List<Integer> askFr = new ArrayList<>();
            List<Integer> askTo = new ArrayList<>();
            cacheIt++;
            // [yFr.. yMid] [yMid + 1..tTo]
            for (int i = 0; i < from.size(); i++) {
                int f1 = first(from.get(i), to.get(i), yFr, yMid);
                int t1 = last(from.get(i), to.get(i), yFr, yMid);
                if (f1 > t1) {
                    join1.add(-1);
                } else {
                    if (cache[f1][t1] != cacheIt) {
                        cache[f1][t1] = cacheIt;
                        cacheVal[f1][t1] = askFr.size();
                        askFr.add(f1);
                        askTo.add(t1);
                    }
                    join1.add(cacheVal[f1][t1]);
                }
            }
            List<Integer> r1 = go(askFr, askTo, yFr, yMid);
            for (int i = 0; i < join1.size(); i++) {
                if (join1.get(i) != -1) {
//                    System.err.println(join1.get(i)+" " + askFr.size());
                    join1.set(i, r1.get(join1.get(i)));
                }
            }
            cacheIt++;
            askFr.clear();
            askTo.clear();
            for (int i = 0; i < from.size(); i++) {
                int f1 = first(from.get(i), to.get(i), yMid + 1, yTo);
                int t1 = last(from.get(i), to.get(i), yMid + 1, yTo);
                if (f1 > t1) {
                    join2.add(-1);
                } else {
                    if (cache[f1][t1] != cacheIt) {
                        cache[f1][t1] = cacheIt;
                        cacheVal[f1][t1] = askFr.size();
                        askFr.add(f1);
                        askTo.add(t1);
                    }
                    join2.add(cacheVal[f1][t1]);
                }
            }
            List<Integer> r2 = go(askFr, askTo, yMid + 1, yTo);
            for (int i = 0; i < join2.size(); i++) {
                if (join2.get(i) != -1) {
                    join2.set(i, r2.get(join2.get(i)));
                }
            }
            List<Integer> res = new ArrayList<>();
            for (int i = 0; i < from.size(); i++) {
                int x = join1.get(i), y = join2.get(i);
                if (x == -1 || y == -1) {
                    res.add(x + y + 1);
                } else {
                    left.add(x);
                    right.add(y);
                    res.add(left.size() - 1);
                }
            }
            return res;
        }
    }

    int[][] cache;
    int[][] cacheVal;
    int cacheIt = 1;
    int[] a;

    void solve() {
        int n = in.nextInt();
        cache = new int[n][n];
        cacheVal = new int[n][n];
        int q = in.nextInt();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt() - 1;
        }

        List<Integer> from = new ArrayList<>();
        List<Integer> to = new ArrayList<>();
        for (int i = 0; i < q; i++) {
            from.add(in.nextInt() - 1);
            to.add(in.nextInt() - 1);
        }
        List<Integer> res = go(from, to, 0, n - 1);
        out.println(n + left.size());
        for (int i = 0; i < left.size(); i++) {
            out.println((left.get(i) + 1) + " " + (right.get(i) + 1));
        }
        for (int i = 0; i < res.size(); i++) {
            out.print((res.get(i) + 1) + " ");
        }
        out.println();
    }

    void run() {
        try {
            in = new FastScanner(new File("H.in"));
            out = new PrintWriter(new File("H.out"));

            solve();

            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    void runIO() {

        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);

        solve();

        out.close();
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        public FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }

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

        boolean hasMoreTokens() {
            while (st == null || !st.hasMoreTokens()) {
                String s = null;
                try {
                    s = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (s == null)
                    return false;
                st = new StringTokenizer(s);
            }
            return true;
        }

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

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

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

    public static void main(String[] args) {
        new H().runIO();
    }
}


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

public class Main{
	static int maxn=1000000;
	static long inf=(long)1e16;
	static long fill=(long)-1e18;
	static ArrayList<Integer>weights;
	static ArrayList<Long>vals;
	static long[]memo;

	static int[]F;
	static long cost(int num) {
		int d=0;
		long ans=0;
		while(num>0) {
			int digit=num%10;
			num/=10;
			if(digit==3 || digit==6 || digit==9) {
				ans+=F[d]*1l*(digit/3);
			}
			d++;
		}
		return ans;
	}
	static void main() throws Exception{
		int n=(sc.nextInt()-1)*3;
		F=sc.intArr(6);
		vals=new ArrayList<Long>();
		weights=new ArrayList<Integer>();
		int ten=1;
		for(int i=0;i<6;i++) {
			int curW=3*ten;long curV=F[i];
			int cur=1;
			int tmpn=n;
			while(cur<=tmpn) {
				if(curW*1l*cur>maxn)break;
				weights.add(curW*cur);
				vals.add(curV*cur);
				tmpn-=cur;
				cur<<=1;
			}
			if(tmpn>0 && curW*1l*tmpn<=maxn) {
				weights.add(curW*tmpn);
				vals.add(curV*tmpn);
			}
			ten*=10;
		}
		memo=new long[maxn];
		for(int i=1;i<maxn;i++) {
			memo[i]=-inf;
		}

		for(int i=0;i<weights.size();i++) {
			long[]newMemo=new long[maxn];
			for(int sum=0;sum<maxn;sum++) {
				int nxtSum=sum-weights.get(i);
				newMemo[sum]=Math.max(memo[sum], vals.get(i)+(nxtSum<0?(-inf):(memo[nxtSum])));
			}
			memo=newMemo;
		}
		int q=sc.nextInt();
		int sum=sc.nextInt();
		long ans=-inf;
		for(int i=0;i<=sum;i++) {
			ans=Math.max(cost(i)+memo[sum-i],ans);
		}
		pw.println(ans);

	}
	public static void main(String[] args) throws Exception{
		sc=new MScanner(System.in);
		pw = new PrintWriter(System.out);
//		int tc=1;
//		tc=sc.nextInt();
//		while(tc-->0)
			main();
		pw.flush();
	}
	static PrintWriter pw;
	static MScanner sc;
	static class MScanner {
		StringTokenizer st;
		BufferedReader br;
		public MScanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public MScanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public int[] intArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public long[] longArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public int[] intSortedArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		public long[] longSortedArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		public Integer[] IntegerArr(int n) throws IOException {
	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public Long[] LongArr(int n) throws IOException {
	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

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

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}

	}
	static void shuffle(int[]in) {
		for(int i=0;i<in.length;i++) {
			int idx=(int)(Math.random()*in.length);
			int tmp=in[i];
			in[i]=in[idx];
			in[idx]=tmp;
		}
	}
	static void shuffle(long[]in) {
		for(int i=0;i<in.length;i++) {
			int idx=(int)(Math.random()*in.length);
			long tmp=in[i];
			in[i]=in[idx];
			in[idx]=tmp;
		}
	}
}


// Problem : E. Vasya's Function
// Contest : Codeforces - Educational Codeforces Round 26
// URL : https://codeforces.com/contest/837/problem/E
// Memory Limit : 256 MB
// Time Limit : 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

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

public class a implements Runnable{

    public static void main(String[] args) {
        new Thread(null, new a(), "process", 1<<26).start();
    }
	public void run() {
		FastReader scan = new FastReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		//PrintWriter out = new PrintWriter("file.out");
		Task solver = new Task();
		//int t = scan.nextInt();
		int t = 1;
		for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
		out.close();
	}

	static class Task {
		static final int inf = Integer.MAX_VALUE;

		public void solve(int testNumber, FastReader sc, PrintWriter pw) {
			//CHECK FOR QUICKSORT TLE
			//***********************//
			//CHECK FOR INT OVERFLOW
			//***********************//
			long a = sc.nextInt();
			long b=  sc.nextInt();
			HashMap<Long, Integer> factors = new HashMap<>();
			for(long i = 2; i * i <= a; i++) {
				if(a%i == 0) {
					factors.put(i, 0);
					while(a % i == 0) {
						a /= i;
						factors.put(i, factors.get(i) + 1);
					}
				}
			}
			if(a > 1) {
				factors.put(a, factors.getOrDefault(a, 0) + 1);
			}
			//pw.println(factors);
			long sum = 0;
			long c = 1;
			while(b > 0) {
				long min = Math.max(1, b);
				long d = 1;
				for(long x : factors.keySet()) {
					long rem = b - (b/(c*x)) * c*x;
					if(min > rem) {
						d = x;
						min = rem;
					}
				}
				if(d > 1) {
					factors.put(d, factors.get(d) - 1);
					if(factors.get(d) == 0) {
						factors.remove(d);
					}
				}
				b -= min;
				sum += min / c;
				c *= d;
				//pw.println(b + " " + c);
			}
			pw.println(sum);

		}
	}
	static long binpow(long a, long b, long m) {
		a %= m;
		long res = 1;
		while (b > 0) {
			if ((b & 1) == 1)
				res = res * a % m;
			a = a * a % m;
			b >>= 1;
		}
		return res;
	}
	static void sort(int[] x){
		shuffle(x);
		Arrays.sort(x);
	}
	static void sort(long[] x){
		shuffle(x);
		Arrays.sort(x);
	}
	static class tup implements Comparable<tup>{
		int a, b;
		tup(int a,int b){
			this.a=a;
			this.b=b;
		}
		@Override
		public int compareTo(tup o){
			return Integer.compare(o.b,b);
		}
	}
	static void shuffle(int[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(i + 1);
			int temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}

	static void shuffle(long[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(i + 1);
			long temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

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

		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.io.*;
import java.util.*;

public class Main {
    static Random random;

    /* public static void main(String[] args){
        new Thread(null, new Template (), "Main", 1<<26).start();
    } */

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
        random = new Random();

        // long timeStamp = System.currentTimeMillis();
        Solver solver = new Solver();
        solver.solve(in, out);
        out.close();
        // System.err.println("TIME: "+(System.currentTimeMillis()-timeStamp)+" ms");
    }

    /* ------------------------------------- START -------------------------------------------- */
    static class Solver {
        private static int mod;
        public void solve(FastScanner in, PrintWriter out) {
            int n = in.nextInt();
            mod = in.nextInt();

            int dp[] = new int[n+1];
            int pref[] = new int[n+1];

            dp[1] = 1;
            pref[1] = 1;

            for(int i = 2; i<=n; i++){
                dp[i] = pref[i-1];

                for(int j = 1; j*j<=i; j++){
                    int l = i/(j+1) + 1;
                    int r = i/j;
                    dp[i] = add(dp[i], mult(r-l+1, dp[j]));

                    if(r != j && r != i){
                        dp[i] = add(dp[i], dp[r]);
                    }
                }

                // int q = 1;
                // while(q < i){
                //     int l = i/(q+1) + 1;
                //     int r = i/q;
                //     // new Debug().d("q", q).d("l", l).d("r", r).d();
                //     dp[i] = add(dp[i], mult(r-l+1, dp[q]));
                //     //if(l == 1) break;
                //     q = i/(l-1);
                // }

                // new Debug().d(i, dp[i]).d();

                pref[i] = add(pref[i-1], dp[i]);
            }

            out.println(dp[n]);
        }

        private int add(int x, int y){
            x += y;
            if(x >= mod) x -= mod;
            return x;
        }

        private int mult(int x, int y){
            long r = (x * (long) y);
            if(r >= mod)
                r %= mod;
            return (int) r;
        }
    }
    /* -------------------------------------- END --------------------------------------------- */

    /* Shuffle function to shuffle before Arrays.sort */
    static void shuffle(int[] arr){
        int swapTemp;
        for(int i = arr.length-1; i>= 1; i--){
            int pos = random.nextInt(i+1);
            if(pos == i) continue;
            {swapTemp = arr[i]; arr[i] = arr[pos]; arr[pos] = swapTemp;}
        }
    }

    /* Fast Input reader */
    static class FastScanner {
        BufferedReader reader;
        StreamTokenizer tokenizer;
        public FastScanner() {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = new StreamTokenizer(reader);
            tokenizer.resetSyntax();
            tokenizer.whitespaceChars(0, 32);
            tokenizer.wordChars(33, 126);
        }
        private void nextToken(){
            try{ tokenizer.nextToken(); }
            catch (Exception e) { e.printStackTrace(); }
        }
        String next() {
            nextToken();
            return tokenizer.sval;
        }
        int nextInt() {
            nextToken();
            return Integer.parseInt(tokenizer.sval);
        }
        long nextLong() {
            nextToken();
            return Long.parseLong(tokenizer.sval);
        }
        double nextDouble() {
            nextToken();
            return Double.parseDouble(tokenizer.sval);
        }
        String nextLine() {
            try{
                String string = reader.readLine();
                return string;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    }
}


import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
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;
		StreamInputReader in = new StreamInputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    public void solve(int testNumber, StreamInputReader in, OutputWriter out) {
        int n = in.readInt(), m = in.readInt();
        int res = 0;
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < m; ++j) {
                if (((i+j)&1) == 1) {
                    ++res;
                }
            }
        }
        System.out.println(Math.max(res, n*m -res));
    }
}

class StreamInputReader extends InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public StreamInputReader(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++];
    }

    }

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(outputStream);
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void close() {
		writer.close();
	}
}

abstract class InputReader {

	public abstract int read();

    public int readInt() {
        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;
    }

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

    }


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;

public class Main {

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

	static class TaskC {
		static boolean visited[]  ;
		static boolean found = false;

		static int steps = 0 ;
		static int n ;
		static boolean memo [][] ;
		static int dp[][] ;
		static char matrix[][] ;
		static ArrayList<Integer> p  ;
		public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException, InterruptedException {
			long n =  Long.valueOf(in.next());
			n--;

			long total =0 ;

			for (int i = 1; i <= n; i*=2)
			{
				double current = 1.0 * (n-i) ;
				current = Math.floor(current/(2.0*i)) ;
				current++ ;
				System.err.println(i+" "+current);
				current*=i ;
				total+=current ;

			}

			System.out.println(total);

		}

		public static int cnt1(int mat[][])  //how many swaps to be a 1 matrix
		{
			int m = mat.length ;
			int c=0 ;
			for (int i = 0; i < mat.length; i++)
			{
				for (int j = 0; j < mat.length; j++)
				{
					int x =  (i*m) +j ;
					if(x%2==0 && mat[i][j]==0)
						c++;
					if(x%2!=0 && mat[i][j]==1)
						c++;

				}
			}
			return c;
		}
		public static int cnt0(int mat[][])
		{
			int m = mat.length ;
			int c=0 ;
			for (int i = 0; i < mat.length; i++)
			{
				for (int j = 0; j < mat.length; j++)
				{
					int x =  (i*m) +j ;
					if(x%2!=0 && mat[i][j]==0)
						c++;
					if(x%2==0 && mat[i][j]==1)
						c++;

				}
			}
			return c;
		}

		public static boolean canFit2(int x1, int y1 , int x2 , int y2 , int x3 , int y3){
			if(x1==x2)
				if(x1==x3)
					return true ;
				else
					return false ;
			else
				if(x1==x3)
					return false ;
				else
				{
					long a = 1l*(y2-y1)*(x3-x2) ;
					long b = 1l*(y3-y2)*(x2-x1) ;

					if(a==b)
						return true;
					else
						return false ;

				}

		}
		public static void shuffle(int c[]){
			if(c.length==1)
				return ;
			for (int i = 0; i < c.length; i++)
			{
				Random rand = new Random();

				int  n = rand.nextInt(c.length-1) + 0;

				int temp = c[i] ;
				c[i] = c[n] ;
				c[n] = temp ;
			}
		}
		public static int binary(ArrayList<Long> arr, int l, int r, long x)   /// begin by 0 and n-1
		{
			if (r>=l)
			{
				int mid = l + (r - l)/2;
				if (arr.get(mid) == x)
					return mid;
				if (arr.get(mid)> x)
					return binary(arr, l, mid-1, x);
				return binary(arr, mid+1, r, x);
			}
			return -1;
		}

		/// searching for the index of first elment greater than x
		public static int binary1(ArrayList<Long> arr , long left) {
			int low = 0, high = arr.size(); // numElems is the size of the array i.e arr.size()
			while (low != high) {
				int mid = (low + high) / 2; // Or a fancy way to avoid int overflow
				if (arr.get(mid) <= left) {
					/* This index, and everything below it, must not be the first element
					 * greater than what we're looking for because this element is no greater
					 * than the element.
					 */
					low = mid + 1;
				}
				else {
					/* This element is at least as large as the element, so anything after it can't
					 * be the first element that's at least as large.
					 */
					high = mid;
				}
			}
			return low ; // return high ;
		}

		private static boolean triangle(int a, int b , int c){
			if(a+b>c && a+c>b && b+c>a)
				return true ;
			else
				return false ;
		}
		private static boolean segment(int a, int b , int c){
			if(a+b==c || a+c==b && b+c==a)
				return true ;
			else
				return false ;
		}
		private static int gcdThing(long a, long b) {
			BigInteger b1 = BigInteger.valueOf(a);
			BigInteger b2 = BigInteger.valueOf(b);
			BigInteger gcd = b1.gcd(b2);
			return gcd.intValue();
		}

		public static boolean is(int i){
			if(Math.log(i)/ Math.log(2) ==(int) (Math.log(i)/ Math.log(2)))
				return true ;
			if(Math.log(i)/ Math.log(3) ==(int) (Math.log(i)/ Math.log(3)) )
				return true ;
			if(Math.log(i)/ Math.log(6) ==(int) (Math.log(i)/ Math.log(6)) )
				return true ;

			return false;

		}
		public static boolean contains(int b[] , int x)
		{
			for (int i = 0; i < b.length; i++)
			{
				if(b[i]==x)
					return true ;
			}
			return false ;
		}
		public static int binary(long []arr , long target , int low , long shift) {
			int high = arr.length;
			while (low != high) {
				int mid = (low + high) / 2;
				if (arr[mid]-shift <= target) {
					low = mid + 1;
				}
				else {
					high = mid;
				}
			}
			return low ; // return high ;
		}
		public static boolean isLetter(char x){
			if(x+0 <=122 && x+0 >=97 )
				return true ;
			else if (x+0 <=90 && x+0 >=65 )
				return true ;
			else return false;
		}
		public static long getPrimes(long x ){
			if(x==2 || x==3 || x==1)
				return 2 ;
			if(isPrime(x))
				return 5 ;
			for (int i = 2; i*i<=x; i++)
			{
				if(x%i==0 && isPrime(i))
					return getPrimes(x/i) ;
			}
			return -1;
		}
		public static String solve(String x){

			int n = x.length() ;
			String y = "" ;
			for (int i = 0; i < n-2; i+=2)
			{
				if(ifPalindrome(x.substring(i, i+2)))
					y+= x.substring(i, i+2) ;
				else
					break ;
			}
			return y+ solve1(x.substring(y.length(),x.length())) ;

		}
		public static String solve1(String x){
			String y = x.substring(0 , x.length()/2) ;
			return "" ;

		}
		public static String reverse(String x){
			String y ="" ;
			for (int i = 0; i < x.length(); i++)
			{
				y  = x.charAt(i) + y ;
			}
			return y ;
		}

		public static boolean ifPalindrome(String x){
			int numbers[] = new int[10] ;
			for (int i = 0; i < x.length(); i++)
			{
				int z = Integer.parseInt(x.charAt(i)+"") ;
				numbers[z] ++ ;
			}
			for (int i = 0; i < numbers.length; i++)
			{
				if(numbers[i]%2!=0)
					return false;
			}
			return true ;
		}

		public static int get(int n){
			return n*(n+1)/2 ;
		}
		//		public static long getSmallestDivisor( long y){
		//			if(isPrime(y))
		//				return -1;
		//
		//			for (long i = 2; i*i <= y; i++)
		//			{
		//				if(y%i ==0)
		//				{
		//					return i;
		//				}
		//			}
		//			return -1;
		//		}
		//		public static void lis(pair []a , int n){
		//			int lis[] = new int[n] ;
		//			Arrays.fill(lis,1) ;
		//
		//			for(int i=1;i<n;i++)
		//				for(int j=0 ; j<i; j++)
		//					if (a[i].y>a[j].y &&  lis[i] < lis[j]+1)
		//						lis[i] = lis[j] + 1;
		//
		//			int max = lis[0];
		//
		//			for(int i=1; i<n ; i++)
		//				if (max < lis[i])
		//					max = lis[i] ;
		//			System.out.println(max);
		//
		//			ArrayList<Integer> s = new ArrayList<Integer>() ;
		//			for (int i = n-1; i >=0; i--)
		//			{
		//				if(lis[i]==max)
		//				{
		//					s.add(a[i].z);
		//					max --;
		//				}
		//			}
		//
		//			for (int i = s.size()-1 ; i>=0 ;  i--)
		//			{
		//				System.out.print(s.get(i)+" ");
		//			}
		//
		//			return  ;
		//		}
		public static int calcDepth(Vertix node){
			if(node.depth>0) return node.depth;
			// meaning it has been updated before;
			if(node.parent != null)
				return 1+ calcDepth(node.parent);
			else
				return -1;
		}

		public static boolean isPrime (long num){
			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;
		}

		public static int[] getDiv(int n)
		{
			int result[] = new int[7] ;
			ArrayList<Integer>  f = new ArrayList<Integer>() ;

			while (n%2==0)
			{
				if(!f.contains(2))f.add(2) ;
				n /= 2;
			}

			// n must be odd at this point.  So we can
			// skip one element (Note i = i +2)
			for (int i = 3; i <= Math.sqrt(n); i+= 2)
			{
				// While i divides n, print i and divide n
				while (n%i == 0)
				{
					if(!f.contains(i))f.add(i);
					n /= i;
				}
			}

			// This condition is to handle the case whien
			// n is a prime number greater than 2
			if (n > 2)
				if(!f.contains(n))f.add(n);

			for (int i = 0, j=0; i < f.size(); i++)
			{
				result[j++]=f.get(i);
			}
			return result ;

		}

		//		public static boolean dfs(Vertix v , int target){
		//			try{
		//				visited[v.i]= true ;
		//			} catch (NullPointerException e)
		//			{
		//				System.out.println(v.i);
		//			}
		//			if(v.i == target)
		//
		//				return true ;
		//			for (int i =0 ; i< v.neighbours.size() ; i++)
		//			{
		//
		//				Vertix child = v.neighbours.get(i) ;
		//				if(child.i == target){
		//					found = true  ;
		//				}
		//				if(visited[child.i]==false){
		//					found |= dfs(child, target) ;
		//				}
		//			}
		//			return found;
		//		}

	}
	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 static class Vertix{
		long i ;
		int depth ;
		ArrayList<Vertix> neighbours ;
		Vertix parent ;
		Vertix child ;

		public Vertix(long i){
			this.i = i ;
			this.neighbours = new ArrayList<Vertix> () ;
			this.parent = null ;
			depth =-1;
			this.child = null ;
		}
	}

	public static class pair implements Comparable<pair>{
		int x ;
		int y ;

		public pair(int x, int y , int z){
			this.x=x ;
			this.y=y ;

		}

		@Override
		public int compareTo(pair p) {
			if(this.x > p.x)
				return 1 ;
			else return -1 ;

		}

	}

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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);
        DeterminedCleanup solver = new DeterminedCleanup();
        solver.solve(1, in, out);
        out.close();
    }

    static class DeterminedCleanup {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long p = in.nextLong();
            long k = in.nextInt();
            int mx = 62;
            long[] coe = new long[mx];
            int d = (int) MathUtils.log(p, k);
            coe[0] = p % k;
            long[] pref = new long[mx];
            pref[0] = coe[0];
            for (int i = 1; i <= d; i++) {
                coe[i] = (p % (MathUtils.binPow(k, i + 1, Long.MAX_VALUE)) - pref[i - 1]) / MathUtils.binPow(k, i, Long.MAX_VALUE);
                pref[i] = MathUtils.binPow(k, i, Long.MAX_VALUE) * coe[i] + pref[i - 1];
            }
            for (int i = 1; i <= d; i += 2) {
                if (coe[i] > 0) {
                    coe[i] = -(k - coe[i]);
                    coe[i + 1]++;
                }
            }
            for (int i = 0; i <= d + 1; i++) {
                if (coe[i] == k) {
                    coe[i] = 0;
                    coe[i + 1]++;
                }
            }
            for (int i = mx - 1; i >= 0; i--) {
                if (coe[i] != 0) {
                    d = i;
                    break;
                }
            }
            out.println(d + 1);
            for (int i = 0; i <= d; i++) {
                out.println(Math.abs(coe[i]));
            }
        }

    }

    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());
        }

    }

    static class MathUtils {
        public static long binPow(long b, long p, long mod) {
            long res = 1;
            while (p > 0) {
                if ((p & 1) == 1) {
                    res *= b;
                    res %= mod;
                }
                b = b * b;
                p >>= 1;
                b %= mod;
            }
            return res;
        }

        public static double log(double val, double base) {
            return Math.log(val) / Math.log(base);
        }

    }
}


import java.util.Scanner;
public class harrypotter {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        int d = scan.nextInt();
        int e = scan.nextInt();
        int f = scan.nextInt();
        if (a == 0 && b == 0 && c == 0 && d == 0 && e == 0 && f == 0)
            System.out.println("Hermione");
        if (c == 0 && d > 0)
            System.out.println("Ron");
        if(c==0&&d==0)
            System.out.println("Hermione");
        if (a == 0 && b != 0 && c != 0 && d != 0)
            System.out.println("Ron");
        if(e==0) {
            if (c == 0 && d > 0)
                System.out.println("Ron");
            if (a == 0 && b != 0 && c != 0 && d != 0)
                System.out.println("Ron");
        }
            if(a==0&&b==0){
                if (c == 0 && d > 0)
                    System.out.println("Ron");
                if(c==0&&d==0)
                    System.out.println("Hermoine");
            }

        if(e==0&&f==0)
            System.out.println("Hermione");
        if(c!=0&&e!=0&&a!0) {
            double sand = (f * d * b) / (e * c*a);
            int value = (int) sand;
            if (value > a)
                System.out.println("Ron");
            else
                System.out.println("Hermione");

        }
    }
    }


import java.util.*;
public class Sol{
    public static void main(string[] args){
        Scanner s=new Scanner(system.in);
        int n=s.nextInt();
        int p=s.nextInt();
        int w=s.nextInt();
        int d=s.nextInt();
        boolean flag=true;
        int x=0;
        int y=0;
        int z=0;
        if(n*w>=p){
            x=p/w;
            p=p%w;
            if(p>=d){
                y=p/d;
                p=p%d;
                if(p>0){
                    flag=false;
                }
            }
            z=n-x-y;
        }
        else{
            flag=false;
        }
        if(!flag){
            System.out.println("-1");
        }
        else{
            System.out.print(x+" "+y+" "+z);
        }

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;

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);
    solve(in,out);
    out.close();
  }

  private static final int MOD = (int)1e9 + 7;

  private static long add(long a, long b) {
	  a += b;
	  if (a >= MOD) {
		  a -= MOD;
	  }
	  return a;
  }

  private static long pow(long a, int b) {
	  long ans = 1;
	  while (b > 0) {
		  if ((b % 2) > 0) {
			  ans = ans * a %MOD;
		  }
		  a = a * a % MOD;
		  b >>= 1;
	  }
	  return ans;
  }

  private static void solve(InputReader in, PrintWriter out) {
	  int n = in.nextInt();
	  long m = in.nextLong();
	  long dp[] = new long[n + 1];
	  dp[0] = 1;
	  for (int i = 1; i <= n; i++) {
		  dp[i] = 0;
		  for (int j = 0; j < i; j++) {
			  dp[i] = add(dp[i], dp[j] * m % MOD * pow(m - 1, i - j - 1) % MOD);
		  }
	  }
	  long ans = 0;
	  for (int i = 0; i <= n; i++) {
		  ans = add(ans, dp[i] * pow(m, n - i) % MOD);
	  }
	  out.print(ans);
  }

  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());
    }

  }
}


import java.util.*;
public class EmailAddress
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		String s=sc.next();

		if(s.charAt(0)=='a' && s.charAt(1)=='t')
		{
			int k=s.indexOf("at",2);
			StringBuilder stb1=new StringBuilder(s);
			stb1=stb1.replace(k,k+2,"@");
			s=stb1.toString();
		}
		else
		{
			int k=s.indexOf("at",2);
			StringBuilder stb1=new StringBuilder(s);
			stb1=stb1.replace(k,k+2,"@");
			s=stb1.toString();
		}

	//	System.out.println("s:" +s);

		s=s.replaceAll("dot",".");
	//	System.out.println("fs:" +s);

		if(s.charAt(0)=='.')
		{
			s=s.replaceFirst(".","dot");
		}

//		System.out.println("SS:"+s);

		StringBuilder stb=new StringBuilder(s);
		if(stb.charAt(stb.length()-1)=='.')
		{
			stb.deleteCharAt(stb.length()-1);
			stb.append("dot");
		}
		System.out.println(stb.toString());

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Abacaba {
    public static void main(String[] args) throws IOException {
        BufferedReader leer= new BufferedReader(new InputStreamReader(System.in));
        String[] line=leer.readLine().split(" ");
        long a=Long.parseLong(line[0])-1;
        long b=Long.parseLong(line[1])-1;
        long c=Long.parseLong(line[2])-1;
        long d=Long.parseLong(line[3])-1;
        long r=solve(a,b,c,d,(long)(Math.pow(2, 4)-1)/2);
        System.out.println(r);
    }
    private static long solve(long a, long b, long c, long d,long m) {
        if(b<a || d<c) return 0;
        long l=longitud(a,b,c,d);
        if( a <= c && b >= d || a >= c && b <= d ) return l ;

        l= Math.max(l, solve(Math.min(a, m),Math.min(b, m-1),Math.min(c,m),Math.min(d, m-1),m/2));
        l= Math.max(l, solve(Math.min(a, m),Math.min(b, m-1),Math.max(c,m+1)-m-1,Math.max(d, m)-m-1,m/2));
        l= Math.max(l, solve(Math.max(a, m+1)-m-1,Math.max(b, m)-m-1,Math.min(c,m),Math.min(d, m-1),m/2));
        l= Math.max(l, solve(Math.max(a, m+1)-m-1,Math.max(b, m)-m-1,Math.max(c,m+1)-m-1,Math.max(d, m)-m-1,m/2));

        return l;
    }

    private static long longitud(long l1, long r1, long l2, long r2) {
        long ovl = Math.max(l1, l2);
        long ovr = Math.min(r1, r2);
        return ( (ovr >= ovl)? (ovr - ovl + 1) : 0 );
    }
}


import java.math.BigInteger;
import java.util.Scanner;

public class AprilFools {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int bi = scan.nextInt();
		System.out.println(1);
	}

}


import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class B {

    public static void main(String[] args) throws IOException {
        in = new StreamTokenizer( new InputStreamReader( System.in ) );
        out = new PrintWriter(System.out);
        int a = nextInt();
        int b= nextInt();
        long sum = culcV(a);
        if(a==b) {
            out.println(sum)
            out.close();
            return;
        }
        long prev = sum;
        int lastOst = ((int)a)%10;
        for(int i = a+1;i<=b;i++) {
            int ost = i%10;
            if(ost != 9) {
                prev = prev -valz[lastOst] + valz[ost];
                sum += prev;

            } else {
                int tmp = i;
                while(tmp > 0) {
                    if(tmp%10 == 9) {
                       tmp=tmp/10;
                    } else {
                      break;
                    }
                }
                if(tmp == 0) {
                   prev+=2;
                   sum+=prev;
                } else {
                   int indx = tmp %10;
                   prev = prev -valz[indx] + valz[indx +1];
                   sum += prev;
                }
            }
            lastOst = ost;
        }
        out.println(sum);
        out.close();
    }

    static long[] valz = new long[] {6,2,5,5,4,5,6,3,7,6};

    static long culcV(int x) {
        long sum = 0;
        while(x>0) {
           int ost = x%10;
           sum += valz[ost];
           x = x/10;
        }
          return sum;
    }

    static StreamTokenizer in;
    static PrintWriter out;

    static int nextInt() throws IOException {
        in.nextToken();
        return ( int ) in.nval;
    }

    static long nextLong() throws IOException {
        in.nextToken();
        return ( long) in.nval;
    }

}


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

public class D {

    public static void main(String[] args) throws IOException {
        InputReader in = new InputReader();
        int n = in.nextInt();
        for (int i = 0; i < 10; i++)
            a[i] = in.nextInt();
        for (int i = 0; i < dp.length; i++)
            for (int j = 0; j < dp[0].length; j++)
                dp[i][j] = -1;
        nCr(110, 110);
        long res = 0;
        for (int i = 1; i <= n; i++)
            res = (res + solve(0, i)) % mod;
        System.out.println(res % mod);
    }

    static int[] a = new int[10];
    static long[][] dp = new long[15][110];

    public static long solve(int at, int rem) {
        if (rem < 0)
            return 0;
        if (rem == 0) {
            for (int i = at; i < 10; i++)
                if (a[i] != 0)
                    return 0;
            return 1;
        }
        if (at == 10)
            return rem == 0 ? 1 : 0;
        if (dp[at][rem] != -1)
            return dp[at][rem];
        long res = 0;
        int n = rem;
        if (at == 0)
            n = rem - 1;
        for (int i = a[at]; i <= n; i++)
            res = (res + (c[n][i] * solve(at + 1, rem - i)) % mod) % mod;
        return dp[at][rem] = res % mod;
    }

    static long[][] c;
    static long mod = 1000000007;

    public static void nCr(int n, int r) {
        c = new long[n + 1][r + 1];
        for (int i = 0; i < n + 1; i++)
            c[i][0] = 1;

        for (int j = 1; j <= r; j++)
            for (int i = j; i <= n; i++)
                c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
    }

    static class InputReader {
        BufferedReader in;
        StringTokenizer st;

        public InputReader() throws IOException {
            in = new BufferedReader(new InputStreamReader(System.in));
            st = new StringTokenizer(in.readLine());
        }

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

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

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
import java.util.Stack;
import java.util.StringTokenizer;

public class E {

	private void solve() throws IOException {
		int nf = nextInt();
		int ne = nextInt();
		int ns = nextInt();
		int rf = nextInt();
		int re = nextInt();
		int rs = nextInt();
		int df = nextInt();
		int de = nextInt();

		int n = nf + ne + ns;
		byte[] a = new byte[n];
		for (int i = 0; i < ns; i++) {
			a[i] = 1;
		}

		int sqrs = rs * rs;

		Comparator<Double> cmp = new Comparator<Double>() {
			@Override
			public int compare(Double o1, Double o2) {
				double d = Math.signum(Math.abs(o1) - Math.abs(o2));
				if (d < 0) {
					return -1;
				} else if (d > 0) {
					return 1;
				} else {
					return 0;
				}
			}
		};

		int t = 2 * ns + 2;
		Double[] p = new Double[t];
		int[] b = new int[n];
		double[] f = new double[n];
		double[] e = new double[n];
		double[][] dp = new double[nf + 1][ne + 1];

		double res = 0;

		while (true) {
			int k = 0;
			int q = 0;
			for (int i = 0; i < n; i++) {
				int x = 1000000 + i / 2;
				if (a[i] == 1) {
					double d = Math.sqrt(sqrs - 1);
					p[k++] = x - d;
					p[k++] = -(x + d);
				} else {
					b[q++] = x;
				}
			}
			p[k++] = 0.0;
			p[k++] = -2000000.0;
			Arrays.sort(p, cmp);

			for (int i = 0; i < q; i++) {
				f[i] = f(p, b[i], df, rf);
				e[i] = f(p, b[i], de, re);
			}

			for (int i = 1; i <= nf; i++) {
				dp[i][0] = dp[i - 1][0] + f[i - 1];
			}
			for (int i = 1; i <= ne; i++) {
				dp[0][i] = dp[0][i - 1] + e[i - 1];
			}

			for (int i = 1; i <= nf; i++) {
				for (int j = 1; j <= ne; j++) {
					dp[i][j] = Math.max(dp[i - 1][j] + f[i + j - 1], dp[i][j - 1] + e[i + j - 1]);
				}
			}

			res = Math.max(res, dp[nf][ne]);

			boolean next = false;
			int ones = 0;
			for (int i = 0; i < a.length - 1; i++) {
				if (a[i] == 0) {
					if (ones != 0) {
						a[i] = 1;
						for (int j = 0; j < ones - 1; j++) {
							a[j] = 1;
						}
						for (int j = ones - 1; j < i; j++) {
							a[j] = 0;
						}
						next = true;
						break;
					}
				} else {
					ones++;
				}
			}

			if (!next) {
				break;
			}
		}

		println(res);
	}

	private double f(Double[] p, int x, double damage, double R) {
		double dx = Math.sqrt(R * R - 1);
		double l = x - dx;
		double r = x + dx;

		double k = 1;
		double res = 0;
		for (int i = 1; i < p.length; i++) {
			double inter = inter(p[i - 1], p[i], l, r);
			res += damage * inter / (1 / k);
			if (p[i] > 0) {
				k++;
			} else {
				k--;
			}
		}

		return res;
	}

	private double inter(double l1, double r1, double l2, double r2) {
		l1 = Math.abs(l1);
		r1 = Math.abs(r1);
		l2 = Math.abs(l2);
		r2 = Math.abs(r2);
		double r = Math.min(r1, r2) - Math.max(l1, l2);
		if (r < 0) {
			return 0;
		} else {
			return r;
		}
	}

	private String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

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

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

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

	private void print(Object o) {
		writer.print(o);
	}

	private void println(Object o) {
		writer.println(o);
	}

	private void printf(String format, Object... o) {
		writer.printf(format, o);
	}

	public static void main(String[] args) {
		long time = System.currentTimeMillis();
		Locale.setDefault(Locale.US);
		new E().run();
		System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	private void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(13);
		}
	}
}


import java.util.*;
import java.io.*;
public class B{

	static TreeMap<Long,Long> getDivisors(long x){
		TreeMap<Long,Long>ans= new TreeMap();

		for(long l=1;l*l<=x;l++)
			if(x%l==0)
				ans.put(l, x/l);

		return ans;
	}
	public static void main(String[] args) throws IOException {
		Scanner sc=new Scanner(System.in);
		PrintWriter  out=new PrintWriter(System.out);
		long a=sc.nextLong(),b=sc.nextLong();
		long area=a+b;
		long ans=Long.MAX_VALUE;
		TreeMap<Long,Long> map=getDivisors(a);
		for(long l=1;l*l<=area;l++)
		{
			if(area%l==0)
			{

				long x=area/l;
				Long  y =map.floorKey(x);
				if(y!=null && map.get(y)<=x) {
					ans=Math.min(ans, x+l);
				}
			}
		}
		 map=getDivisors(b);
		for(long l=1;l*l<=area;l++)
		{
			if(area%l==0)
			{

				long x=area/l;
				Long  y =map.floorKey(x);
				if(y!=null && map.get(y)<=x) {
					ans=Math.min(ans, x+l);
				}
			}
		}
		out.println(ans*2);
		out.close();
	}

	static class Scanner {
        StringTokenizer st;
        BufferedReader br;

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

        public Scanner(FileReader s) {
            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 boolean ready() throws IOException {return br.ready();}
        public double nextDouble() throws IOException {return Double.parseDouble(next());}

    }

}


import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Task {

    public static void solve() throws Exception {
	long maxSum = nextLong();
	long[] arr = new long[9];
	for (int i = 1; i <= 8; i++) {
	    arr[i] = nextLong();
	}
	leaveMax4(arr);

	long sum = 0;
	long safeSum = maxSum - 100;
	if (safeSum > 0) {
	    for (int i = arr.length - 1; i >= 1; i--) {
		long cnt = (safeSum - sum) / i;
		boolean done = false;
		if (cnt <= arr[i]) {
		    done = true;
		}
		cnt = Math.min(cnt, arr[i]-60);
		sum += cnt * i;
		arr[i] -= cnt;
		if (done) {
		    break;
		}
	    }
	}
	System.out.println(go(arr, sum, maxSum, 8));
    }

    private static long go(long[] arr, long sum, long maxSum, int ind) {
	long max = sum;
	for (long i = 0; i <= arr[ind]; i++) {
	    long v = sum + i * ind;
	    if (v == maxSum) {
		return maxSum;
	    } else if (v > maxSum) {
		break;
	    } else {
		if (ind > 1) {
		    v = go(arr, v, maxSum, ind - 1);
		}
		if (v == maxSum) {
		    return maxSum;
		}
		if (v > max) {
		    max = v;
		}
	    }
	}
	return max;
    }

    private static void leaveMax4(long[] arr) {
	for (int i = 1; i < arr.length; i++) {
	    if (arr[i] > 0) {
		for (int j = i + 1; j < arr.length; j++) {
		    if (arr[j] > 0) {
			int mod = j % i;
			if (mod == 0) {
			    int x = j / i;
			    if (arr[i] >= x - 1) {
				arr[i] += x * arr[j];
				arr[j] = 0;
			    }
			}
		    }
		}
	    }
	}
	int count = 0;
	for (int i = 1; i < arr.length; i++) {
	    if (arr[i] > 0) {
		count++;
	    }
	}
	if (count > 4) {
	    throw new RuntimeException();
	}
    }

    public static void main(String[] args) throws Exception {
	try {
	    fastReader = new FastReader(System.in);
	    systemOut = new BufferedOutputStream(System.out);
	    solve();
	} finally {
	    systemOut.close();
	}
    }

    private static FastReader fastReader = null;
    private static BufferedOutputStream systemOut = null;

    public static void print(Object obj) {
	print(obj.toString());
    }

    public static void print(String str) {
	try {
	    systemOut.write(str.getBytes("utf-8"));
	} catch (Exception ex) {
	    throw new RuntimeException(ex);
	}
    }

    public static void println(Object obj) {
	println(obj.toString());
    }

    public static void println(String str) {
	try {
	    print(str);
	    systemOut.write('\n');
	} catch (Exception ex) {
	    throw new RuntimeException(ex);
	}
    }

    public static String next() {
	return fastReader.readNextToken(false);
    }

    public static String nextLine() {
	return fastReader.readNextToken(true);
    }

    public static int nextInt() {
	return Integer.parseInt(fastReader.readNextToken(false));
    }

    public static long nextLong() {
	return Long.parseLong(fastReader.readNextToken(false));
    }

    public static double nextDouble() {
	return Double.parseDouble(fastReader.readNextToken(false));
    }

    static class FastReader {
	private byte[] buf = new byte[65536];
	private int ind = 0;
	private int maxInd = -1;
	private InputStream is = null;
	private boolean eof = false;
	private boolean lastCharRead = false;

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

	public String readNextToken(boolean endOfLine) {
	    try {
		StringBuilder sb = new StringBuilder();
		boolean found = false;
		while (true) {
		    if (lastCharRead) {
			return null;
		    } else if (ind > maxInd) {
			if (eof) {
			    lastCharRead = true;
			} else {
			    fillBuffer();
			}
		    }
		    byte b = '\n';
		    if (!lastCharRead) {
			b = buf[ind++];
		    }

		    if (b == '\r') {
			// ignore
		    } else if ((b == '\n' && endOfLine) || (Character.isWhitespace(b) && !endOfLine)) {
			if (found) {
			    break;
			}
		    } else {
			sb.append((char) b);
			found = true;
		    }
		}
		return sb.toString();
	    } catch (Exception ex) {
		throw new RuntimeException(ex);
	    }
	}

	private void fillBuffer() {
	    try {
		int read = is.read(buf, 0, buf.length);
		if (read < buf.length) {
		    eof = true;
		}
		ind = 0;
		maxInd = read - 1;
	    } catch (Exception ex) {
		throw new RuntimeException(ex);
	    }
	}
    }
}


public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int q = in.nextInt();
        Map<String,String> map = new HashMap<>();
        for(int i = 0; i < q; i++){
            map.put(in.next, in.next);
        }
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            System.out.println(entry.getKey() + "/" + entry.getValue());
        }
    }
}