package codeforces.c197;

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

public class ETry implements Runnable {

    private PrintWriter out = new PrintWriter(System.out, true);
    private Scanner scanner;

    int n;
    int[] size;
    int[] parent;
    PointWI[] points;
    int[] ans;

    Graph graph;

    @Override
    public void run() {
        n = scanner.nextInt();
        // читаем граф
        graph = new Graph(n);

        for (int i = 0; i < n - 1; i++) {
            int x = scanner.nextInt() - 1;
            int y = scanner.nextInt() - 1;
            graph.addEdge(x, y);
        }

        // читаем точки
        points = new PointWI[n];
        for (int i = 0; i < n; i++) {
            points[i] = new PointWI(scanner.nextLong(), scanner.nextLong(), i);
        }

        // подвешиваем дерево и
        size = new int[n];
        parent = new int[n];
        dfs(0, -1);

        // считаем ответ
        ans = new int[n];
        Arrays.fill(ans, -1);

        // ищем самый левый
        List<PointWI> pointsList = Arrays.asList(points);

        PointWI min = Collections.min(pointsList, new MostLeftPointComparator());
        Collections.swap(pointsList, 0, min.i);

        // считаем
        rec(0, 0, n - 1);

        // ответ
        for (int i = 0; i < n; i++) {
            out.print(ans[i] + 1);
            if (i == n - 1) {
                out.println();
            } else {
                out.print(" ");
            }
        }
    }

    private void rec(int x, int left, int right) {
        ans[points[left].i] = x;
        Arrays.sort(points, left + 1, right + 1, new PointComparator(points[left]));
        int i = left + 1;
        for (int y : graph.adjacent(x)) {
            if (y != parent[x]) {
                rec(y, i, i + size[y] - 1);
                i += size[y];
            }
        }
    }

    private void dfs(int x, int p) {
        parent[x] = p;
        size[x] = 1;
        for (int y : graph.adjacent(x)) {
            if (y != p) {
                dfs(y, x);
                size[x] += size[y];
            }
        }
    }

    public ETry setInput(InputStream inputStream) {
        this.scanner = new Scanner(inputStream);
        return this;
    }

    public static void main(String[] args) {
        new ETry().setInput(System.in).run();
    }
}

class Graph {
    private final int n;
    private final List<List<Integer>> adj;

    public Graph(int n) {
        this.n = n;
        this.adj = new ArrayList<List<Integer>>(n);
        createAdjList(n);
    }

    private void createAdjList(int n) {
        while (n > 0) {
            this.adj.add(new ArrayList<Integer>());
            n--;
        }
    }

    public void addEdge(int v, int u) {
        adj.get(v).add(u);
        adj.get(u).add(v);
    }

    public Iterable<Integer> adjacent(int v) {
        return adj.get(v);
    }

    public int getN() {
        return n;
    }
}

//solution

class PointWI {
    long x, y;
    int i;

    public PointWI(long x, long y, int i) {
        this.x = x;
        this.y = y;
        this.i = i;
    }

    @Override
    public String toString() {
        return String.format("[(%d %d) %d]", x, y, i);
    }

}

class MostLeftPointComparator implements Comparator<PointWI> {
    @Override
    public int compare(PointWI p1, PointWI p2) {
        int byx = compare(p1.x, p2.x);
        if (byx == 0) {
            return compare(p1.y, p2.y);
        }
        return byx;
    }

    public static int compare(long a, long b) {
        return a < b ? -1 : (a == b ? 0 : 1);
    }
}

class PointComparator implements Comparator<PointWI> {
    PointWI root;

    public PointComparator(PointWI root) {
        this.root = root;
    }

    @Override
    public int compare(PointWI a, PointWI b) {
        long wp = (a.x - root.x) * (b.y - root.y) - (a.y - root.y) * (b.x - root.x);
        if (wp < 0)
            return -1;
        if (wp > 0)
            return 1;
        return 0;
    }
}


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

public class ETry implements Runnable {

    private PrintWriter out = new PrintWriter(System.out, true);
    private Scanner scanner;

    public ETry setInput(InputStream inputStream) {
        this.scanner = new Scanner(inputStream);
        return this;
    }

    public static void main(String[] args) {
        new E().setInput(System.in).run();
    }

    // solution

    class Point {
        long x, y;
        int i;

        public Point(long x, long y, int i) {
            this.x = x;
            this.y = y;
            this.i = i;
        }

        @Override
        public String toString() {
            return String.format("[(%d %d) %d]", x, y, i);
        }

    }

    class PointComparator implements Comparator<Point> {
        Point root;

        public PointComparator(Point root) {
            this.root = root;
        }

        @Override
        public int compare(Point a, Point b) {
            long wp = (a.x - root.x) * (b.y - root.y) - (a.y - root.y) * (b.x - root.x);
            if (wp < 0)
                return -1;
            if (wp > 0)
                return 1;
            return 0;
        }

    }

    int n;
    List<Integer>[] graph;
    int[] size;
    int[] parent;
    Point[] points;
    int[] ans;

    @Override
    public void run() {
        n = scanner.nextInt();
        // читаем граф
        graph = new List[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < n - 1; i++) {
            int x = scanner.nextInt() - 1;
            int y = scanner.nextInt() - 1;
            graph[x].add(y);
            graph[y].add(x);
        }

        // читаем точки
        points = new Point[n];
        for (int i = 0; i < n; i++) {
            points[i] = new Point(scanner.nextLong(), scanner.nextLong(), i);
        }

        // подвешиваем дерево и
        size = new int[n];
        parent = new int[n];
        dfs(0, -1);

        // считаем ответ
        ans = new int[n];
        Arrays.fill(ans, -1);

        // ищем самый левый
        int rootIndex = 0;
        for (int i = 1; i < n; i++) {
            if (points[i].x < points[rootIndex].x || points[i].x == points[rootIndex].x
                    && points[i].y < points[rootIndex].y) {
                rootIndex = i;
            }
        }

        // ставим самый левый первым
        Point tmp = points[0];
        points[0] = points[rootIndex];
        points[rootIndex] = tmp;

        // считаем
        rec(0, 0, n - 1);

        // ответ
        for (int i = 0; i < n; i++) {
            out.print(ans[i] + 1);
            if (i == n - 1) {
                out.println();
            } else {
                out.print(" ");
            }
        }
    }

    private void rec(int x, int left, int right) {
        ans[points[left].i] = x;
        Arrays.sort(points, left + 1, right + 1, new PointComparator(points[left]));
        int i = left + 1;
        for (int y : graph[x]) {
            if (y != parent[x]) {
                rec(y, i, i + size[y] - 1);
                i += size[y];
            }
        }
    }

    private void dfs(int x, int p) {
        parent[x] = p;
        size[x] = 1;
        for (int y : graph[x]) {
            if (y != p) {
                dfs(y, x);
                size[x] += size[y];
            }
        }
    }

}


import java.util.Scanner;

public class E {
    static long mod = 998244353;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long n = in.nextInt();
        long m = in.nextInt();
        long p = in.nextInt();
        long q = in.nextInt();
        long x = q - p + 1;
        if (p % 2 == 0) x = x - x / 2;
        else x /= 2;
        long y = q - p + 1 - x;
        if ((n & m) % 2 == 0) {
            long ans = fn(x, y, n * m, 0);
            System.out.println(ans);
        } else {
            long ans = bin(x + y, n * m);
            System.out.println(ans);
        }
    }

    private static long fn(long x, long y, long st, int type) {
        if (st == 1) {
            if (type == 0) return x;
            return y;
        }
        if (st % 2 == 1) {
            return (x * fn(x, y, st - 1, type) + y * fn(x, y, st - 1, (type + 1) % 2)) % mod;
        } else {
            long nch = fn(x, y, st / 2, 1);
            long ch = fn(x, y, st / 2, 0);
            if (type == 0) {
                return ((ch * ch) % mod + (nch * nch) % mod) % mod;
            } else {
                return (2 * ch * nch) % mod;
            }
        }
    }

    private static long bin(long x, long st) {
        if (st == 0) return 1;
        if (st == 1) return x;
        long m = st / 2;
        long ans = bin(x, m);
        if (st % 2 == 0) {
            return (ans * ans) % mod;
        } else {
            return (((ans * ans) % mod) * x) % mod;
        }
    }
}


import java.util.Scanner;

public class E {
    static long mod = 998244353;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long n = in.nextInt();
        long m = in.nextInt();
        long p = in.nextInt();
        long q = in.nextInt();
        long x = q - p + 1;
        if (p % 2 == 0) x = x - x / 2;
        else x /= 2;
        long y = q - p + 1 - x;
        if ((n & m) % 2 == 0) {
            long ans = fn(x, y, n * m, 0);
            System.out.println(ans);
        } else {
            long ans = bin(x + y, n * m);
            System.out.println(ans);
        }
    }

    private static long fn(long x, long y, long st, int type) {
        if (st == 1) {
            if (type == 0) return x;
            return y;
        }
        if (st % 2 == 1) {
            return (x * fn(x, y, st - 1, type) + y * fn(x, y, st - 1, (type + 1) % 2)) % mod;
        } else {
            long nch = fn(x, y, st / 2, 1);
            long ch = fn(x, y, st / 2, 0);
            if (type == 0) {
                return (ch * ch + nch * nch) % mod;
            } else {
                return (2 * ch * nch) % mod;
            }
        }
    }

    private static long bin(long x, long st) {
        if (st == 0) return 1;
        if (st == 1) return x;
        long m = st / 2;
        long ans = bin(x, m);
        if (st % 2 == 0) {
            return (ans * ans) % mod;
        } else {
            return (((ans * ans) % mod) * x) % mod;
        }
    }
}


package Div2_630;
//564 558 305171115 960941497

import java.util.Scanner;

public class E {
    static long mod = 998244353;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long n = in.nextInt();
        long m = in.nextInt();
        long p = in.nextInt();
        long q = in.nextInt();
        long x = q - p + 1;
        if (p % 2 == 0) x = x - x / 2;
        else x /= 2;
        long y = q - p + 1 - x;
        if ((n & m) % 2 == 0) {
            long ans = fn(x, y, n * m, 0);
            System.out.println(ans);
        } else {
            long ans = bin(x + y, n * m);
            System.out.println(ans);
        }
    }

    static int N = 2000_000;
    static int dp[][] = new int[N][2];

    private static long fn(long x, long y, long st, int type) {
        if (st < N) {
            if (dp[(int) st][type] != 0) return dp[(int) st][type];
        }
        if (st == 1) {
            if (type == 0) return x;
            return y;
        }
        if (st % 2 == 1) {
            return (x * fn(x, y, st - 1, type) + y * fn(x, y, st - 1, (type + 1) % 2)) % mod;
        } else {
            long nch = fn(x, y, st / 2, 1);
            long ch = fn(x, y, st / 2, 0);
            long ans = 0;
            if (type == 0) {
                ans = (ch * ch + nch * nch) % mod;
            } else {
                ans = (2 * ch * nch) % mod;
            }
            if (st < N) {
                dp[(int) st][type] = (int) ans;
            }
            return ans;
        }
    }

    private static long bin(long x, long st) {
        if (st == 0) return 1;
        if (st == 1) return x;
        long m = st / 2;
        long ans = bin(x, m);
        if (st % 2 == 0) {
            return (ans * ans) % mod;
        } else {
            return (((ans * ans) % mod) * x) % mod;
        }
    }
}


import org.omg.PortableServer.POA;

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

public class Abc {
    public static void main(String[] args) throws Exception {
        FastReader sc = new FastReader();
        StringBuilder sb=new StringBuilder();
        int t=sc.nextInt();
        while(t-->0) {
            int cheka=sc.nextInt(),chkb=sc.nextInt(),chkc=sc.nextInt(),d=sc.nextInt();
            int x=sc.nextInt(),y=sc.nextInt(),x1=sc.nextInt(),y1=sc.nextInt(),x2=sc.nextInt(),y2=sc.nextInt();
            int adadad=Math.abs(cheka-chkb);
            int dasdasds=Math.abs(chkc-d);
            boolean l=false,dd=false;
            if(cheka>chkb && x-(cheka-chkb)>=x1){
                l=true;
            }
            else if(chkb>cheka && x+(chkb-cheka)<=x2){
                l=true;
            }
            else if(cheka==chkb && (cheka==0 || x-1>=x1 || x+1<=x2))l=true;

            if(chkc>d && y-(chkc-d)>=y1){
                dd=true;
            }
            else if(d>chkc && y+(d-chkc)<=y2)dd=true;
            else if(d==chkc && (chkc==0 || y-1>=y1 || y+1<=y2))dd=true;

            if(l && dd) System.out.println("YES");
            else System.out.println("NO");
        }

    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Scanner;

public class CF_Edu_108_F {
	static boolean verb=true;
	static void log(Object X){if (verb) System.err.println(X);}
	static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
	static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}

	static InputReader reader;

	static class Composite {
		int msk;
		int cost;

		Composite left;
		Composite right;

	}

	static String name(int w) {
		int it=0;
		String s="key:[";
		while (w>0) {
			if ((w&1)!=0) {
				s+=(it+1)+" ";
			}
			w>>=1;
			it++;
		}
		return s+"]";
	}

	static	int FX=Integer.MAX_VALUE;
	static int solveAlt(int[] a,int[] b,int[][] c) {
		int n=a.length;
		int m=b.length;
		int MX=1<<m;

		int tot=0;
		for (int i=0;i<n;i++)
			tot+=a[i];
		int bob=0;
		for (int j=0;j<m;j++)
			bob+=b[j];
		if (tot>bob)
			return -1;

		int[][] cost=new int[n][MX];
		int[] bill=new int[MX];

		for (int w=0;w<MX;w++)
			for (int j=0;j<m;j++)
				if (((1<<j)&w)!=0) {
					bill[w]+=b[j];
					for (int i=0;i<n;i++)
						cost[i][w]+=c[i][j];
				}

		int[] stack=new int[n];
		int[] ptr=new int[n];
		Arrays.fill(ptr, 1);
		int best=FX;
		int st=0;
		int[] curspend=new int[n];

		while (st>=0) {
			if (ptr[st]<MX) {
				int w=ptr[st]++;
				int spend=0;
				if (st>0)
					spend=curspend[st-1];
				//log("trying :"+name(w)+" at pos:"+st);
				//log((bill[w]-a[st])+"  "+(spend+cost[st][w])+" vs "+best);
				if (bill[w]>=a[st] && spend+cost[st][w]<best) {
					// now check all the previous ones
					int TX=1<<st;
					boolean ok=true;
					for (int z=1;z<TX;z++) {
						int gain=a[st];
						int msk=w;
						for (int j=0;j<st;j++) {
							if ((z&(1<<j))!=0) {
								msk|=stack[j];
								gain+=a[j];
							}
						}
						if (gain>bill[msk]) {
							ok=false;
							break;
						}

					}
					if (ok) {
						spend+=cost[st][w];
						curspend[st]=spend;
						if (st==n-1) {
							//log("this is ok");
							stack[st]=w;
							//for (int x:stack) {
							//	log(name(x));
							//}
							best=spend;
						} else {
							stack[st++]=w;
						}
					}

				}
			} else {
				ptr[st]=1;
				st--;
			}
		}

		if (best==FX)
			best=-1;
		return best;

	}
	static int solveKO(int[] a,int[] b,int[][] c) {
		int n=a.length;
		int m=b.length;
		int MX=1<<m;

		int[][] cost=new int[n][MX];
		int[] bill=new int[MX];

		for (int w=0;w<MX;w++)
			for (int j=0;j<m;j++)
				if (((1<<j)&w)!=0) {
					bill[w]+=b[j];
					for (int i=0;i<n;i++)
						cost[i][w]+=c[i][j];
				}

		int VX=m*4+1;
		int[][] spend=new int[MX][VX];

		for (int w=0;w<MX;w++) {
			Arrays.fill(spend[w], FX);
			if (bill[w]>=a[0]) {
				// ok for me
				// now we look at the previous
				spend[w][bill[w]-a[0]]=cost[0][w];
				//log("adding:"+w);
			}
		}

		// this is taking some shortcut...

		for (int i=1;i<n;i++) {
			int[][] nxt=new int[MX][VX];
			for (int w=0;w<MX;w++)
				Arrays.fill(nxt[w],FX);
			for (int w=0;w<MX;w++) {
				if (bill[w]>=a[i]) {
					//log("considering:"+w);
					// ok for me
					// now we look at the previous
					for (int u=0;u<MX;u++)
						for (int v=0;v<VX;v++) {
							if (spend[u][v]<FX) {
								//log("----interested by u:"+u);
								int nu=u|w;
								int nv=v+bill[w]-bill[w&u]-a[i];
								//log("nv:"+nv);
								if (nv>=0) {
									//log("----merging");
									nxt[nu][nv]=Math.min(spend[u][v]+cost[i][w], nxt[nu][nv]);
								}
							}
						}
				}

			}
			spend=nxt;
		}
		int ans=FX;
		for (int w=0;w<MX;w++)
			for (int v=0;v<VX;v++)
				ans=Math.min(ans, spend[w][v]);

		if (ans==FX)
			ans=-1;
		return ans;
	}

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

		reader=new InputReader(System.in);
		int n=reader.readInt();
		int m=reader.readInt();
		int[] a=new int[n];
		int tot=0;
		for (int i=0;i<n;i++) {
			a[i]=reader.readInt();
			tot+=a[i];
		}
		int[] b=new int[m];
		for (int i=0;i<m;i++)
			b[i]=reader.readInt();

		int[][] c=new int[n][m];
		for (int i=0;i<n;i++)
			for (int j=0;j<m;j++)
				c[i][j]=reader.readInt();

		int ans=solveAlt(a,b,c);

		System.out.println(ans);

	}

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

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

		private int read() throws IOException {
			if (curChar >= numChars) {
				curChar = 0;
				numChars = stream.read(buf);
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public final String readString() throws IOException {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res=new StringBuilder();
			do {
				res.append((char)c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public final int readInt() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			int res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

		public final long readLong() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			long res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

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


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Scanner;

public class CF_Edu_108_F {
	static boolean verb=true;
	static void log(Object X){if (verb) System.err.println(X);}
	static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
	static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}

	static InputReader reader;

	static class Composite {
		int msk;
		int cost;

		Composite left;
		Composite right;

	}

	static String name(int w) {
		int it=0;
		String s="key:[";
		while (w>0) {
			if ((w&1)!=0) {
				s+=(it+1)+" ";
			}
			w>>=1;
			it++;
		}
		return s+"]";
	}

	static	int FX=Integer.MAX_VALUE;
	static int solveAlt(int[] a,int[] b,int[][] c) {
		int n=a.length;
		int m=b.length;
		int MX=1<<m;

		int tot=0;
		for (int i=0;i<n;i++)
			tot+=a[i];
		int bob=0;
		for (int j=0;j<m;j++)
			bob+=b[j];
		if (tot>bob)
			return -1;

		int[][] cost=new int[n][MX];
		int[] bill=new int[MX];

		for (int w=0;w<MX;w++)
			for (int j=0;j<m;j++)
				if (((1<<j)&w)!=0) {
					bill[w]+=b[j];
					for (int i=0;i<n;i++)
						cost[i][w]+=c[i][j];
				}

		int[] stack=new int[n];
		int[] ptr=new int[n];
		Arrays.fill(ptr, 1);
		int best=FX;
		int st=0;
		int[] curspend=new int[n];

		while (st>=0) {
			if (ptr[st]<MX) {
				int w=ptr[st]++;
				int spend=0;
				if (st>0)
					spend=curspend[st-1];
				if (bill[w]>=a[st] && spend+cost[st][w]<best) {
					boolean ok=true;
					for (int z=1;z<(1<<st) && ok;z++) {
						int gain=a[st];
						int msk=w;
						for (int j=0;j<st;j++) {
							if ((z&(1<<j))!=0) {
								msk|=stack[j];
								gain+=a[j];
							}
						}
						if (gain>bill[msk])
							ok=false;
					}
					if (ok) {
						spend+=cost[st][w];
						curspend[st]=spend;
						if (st==n-1) {
							best=spend;
						} else {
							stack[st++]=w;
						}
					}
				}
			} else {
				ptr[st]=1;
				st--;
			}
		}

		if (best==FX)
			best=-1;
		return best;

	}

	static int bst;

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

		reader=new InputReader(System.in);
		int n=reader.readInt();
		int m=reader.readInt();
		int[] a=new int[n];
		int tot=0;
		for (int i=0;i<n;i++) {
			a[i]=reader.readInt();
			tot+=a[i];
		}
		int[] b=new int[m];
		for (int i=0;i<m;i++)
			b[i]=reader.readInt();

		int[][] c=new int[n][m];
		for (int i=0;i<n;i++)
			for (int j=0;j<m;j++)
				c[i][j]=reader.readInt();

		int ans=solveAlt(a,b,c);

		System.out.println(ans);

	}

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

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

		private int read() throws IOException {
			if (curChar >= numChars) {
				curChar = 0;
				numChars = stream.read(buf);
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public final String readString() throws IOException {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res=new StringBuilder();
			do {
				res.append((char)c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public final int readInt() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			int res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

		public final long readLong() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			long res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

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


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Scanner;

public class CF_Edu_108_F {
	static boolean verb=true;
	static void log(Object X){if (verb) System.err.println(X);}
	static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
	static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
	static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}

	static InputReader reader;

	static class Composite {
		int msk;
		int cost;

		Composite left;
		Composite right;

	}

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

		log(1<<6);
		reader=new InputReader(System.in);
		int n=reader.readInt();
		int m=reader.readInt();
		int[] a=new int[n];
		int tot=0;
		for (int i=0;i<n;i++) {
			a[i]=reader.readInt();
			tot+=a[i];
		}
		int[] b=new int[m];
		for (int i=0;i<m;i++)
			b[i]=reader.readInt();

		int[][] c=new int[n][m];
		for (int i=0;i<n;i++)
			for (int j=0;j<m;j++)
				c[i][j]=reader.readInt();

		int MX=1<<m;

		int[][] cost=new int[n][MX];
		int[] bill=new int[MX];

		for (int w=0;w<MX;w++)
			for (int j=0;j<m;j++)
				if (((1<<j)&w)!=0) {
					bill[w]+=b[j];
					for (int i=0;i<n;i++)
						cost[i][w]+=c[i][j];
				}

		int FX=Integer.MAX_VALUE;
		int VX=m*4+1;
		int[][] spend=new int[MX][VX];

		for (int w=0;w<MX;w++) {
			Arrays.fill(spend[w], FX);
			if (bill[w]>=a[0]) {
				// ok for me
				// now we look at the previous
				spend[w][bill[w]-a[0]]=cost[0][w];
				//log("adding:"+w);
			}
		}

		for (int i=1;i<n;i++) {
			int[][] nxt=new int[MX][VX];
			for (int w=0;w<MX;w++)
				Arrays.fill(nxt[w],FX);
			for (int w=0;w<MX;w++) {
				if (bill[w]>=a[i]) {
					//log("considering:"+w);
					// ok for me
					// now we look at the previous
					for (int u=0;u<MX;u++)
						for (int v=0;v<VX;v++) {
							if (spend[u][v]<FX) {
								//log("----interested by u:"+u);
								int nu=u|w;
								int nv=v+bill[w]-bill[w&u]-a[i];
								//log("nv:"+nv);
								if (nv>=0) {
									//log("----merging");
									nxt[nu][nv]=Math.min(spend[u][v]+cost[i][w], nxt[nu][nv]);
								}
							}
						}
				}

			}
			spend=nxt;
		}
		int ans=FX;
		for (int w=0;w<MX;w++)
			for (int v=0;v<VX;v++)
				ans=Math.min(ans, spend[w][v]);

		if (ans==FX)
			ans=-1;
		System.out.println(ans);

}

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

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

	private int read() throws IOException {
		if (curChar >= numChars) {
			curChar = 0;
			numChars = stream.read(buf);
			if (numChars <= 0) {
				return -1;
			}
		}
		return buf[curChar++];
	}

	public final String readString() throws IOException {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res=new StringBuilder();
		do {
			res.append((char)c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public final int readInt() throws IOException {
		int c = read();
		boolean neg=false;
		while (isSpaceChar(c)) {
			c = read();
		}
		char d=(char)c;
		//log("d:"+d);
		if (d=='-') {
			neg=true;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		//log("res:"+res);
		if (neg)
			return -res;
		return res;

	}

	public final long readLong() throws IOException {
		int c = read();
		boolean neg=false;
		while (isSpaceChar(c)) {
			c = read();
		}
		char d=(char)c;
		//log("d:"+d);
		if (d=='-') {
			neg=true;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		//log("res:"+res);
		if (neg)
			return -res;
		return res;

	}

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


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * @authod Rashedul Hasan Rijul
 */
public class Solution {

    int n;
    int mass[];
    int dp[][];
    int cnt[] = new int[102];

    List<Integer> masses = new ArrayList<>();
    List<Integer> cnts = new ArrayList<>();

    public Solution() {

    }

    public Solution(int n) {
        this.n = n;
        mass = new int[n];
        dp = new int[(n * 100) + 1][101];

        for (int i = 0; i <= 100; i++) {
            cnt[i] = 0;
        }

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

                dp[i][j] = 0;

            }
        }
    }

    public static void main(String args[]) throws FileNotFoundException {

        // for testing in local
        // FastReader fastReader = FastReader.getFileReader("in.txt");

        FastReader fastReader = FastReader.getDefaultReader();

        int n = fastReader.nextInt();

        Solution soln = new Solution(n);

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

            soln.mass[i] = fastReader.nextInt();
            soln.cnt[soln.mass[i]]++;
        }

        for (int i = 1; i <= 100; i++) {
            if (soln.cnt[i] > 0) {
                soln.masses.add(i);
                soln.cnts.add(soln.cnt[i]);
            }
        }

        soln.getAnswer();

    }

    public long cal() {

        int tot = 0;
        for (int i = 0; i < n; i++) {
            tot += mass[i];
        }

        dp[0][0] = 1;

        for (int i = 0; i < masses.size(); i++) {
            int coin = masses.get(i);
            for (int k = n; k >= 1; k--) {
                for (int j = cnt[coin]; j >= 1; j--) {
                    if(j>k){
                        continue;
                    }
                    int value = coin * j;
                    for (int l = tot; l >= value; l--) {

                        dp[l][k] += dp[l - value][k - j];
                    }
                }
            }
        }

        return 0;
    }

    public void getAnswer() {

        cal();

        int answer = 0;
        int resultCoin = -1;

        for (int i = 0; i < 100; i++) {
            for (int j = cnt[i]; j > 0; j--) {
                if (j <= answer) {
                    break;
                }
                int value = i * j;

                if (dp[value][j] == 1) {
                    if (answer < j) {
                        answer = j;
                        resultCoin = i;
                    }

                }
            }
        }

        int remCoin = 0;
        int otherCoin = 0;
        for (int i = 0; i < masses.size(); i++) {
            if (masses.get(i).equals(resultCoin)) {
                continue;
            }
            otherCoin++;
        }

        if (cnt[resultCoin] == answer && otherCoin == 1) {
            answer = n;
        }

        System.out.println(answer);
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

        public static FastReader getFileReader(String fileName) throws FileNotFoundException {
            return new FastReader(new InputStreamReader(new FileInputStream(new File(fileName))));
        }

        public static FastReader getDefaultReader() throws FileNotFoundException {
            return new FastReader();
        }

        public FastReader(InputStreamReader inputStreamReader) {
            br = new BufferedReader(inputStreamReader);
        }

        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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Wolfgang Beyer
 */
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);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int[] w = in.read1BasedIntArray(n);
            int sum = 0;
            Set<Integer> wTypes = new HashSet<>();
            for (int i = 1; i <= n; i++) {
                sum += w[i];
                wTypes.add(w[i]);
            }
            if (wTypes.size() < 3) {
                out.println(n);
                return;
            }
            Arrays.sort(w);

            int[][] dp = new int[n + 1][sum + 1];
            int sames = 0;
            for (int i = 1; i <= n; i++) {
                sames++;
                if (i < n && w[i + 1] == w[i]) {
                    continue;
                }

                for (int j = i - 1; j > 0; j--) {
                    for (int k = 1; k <= sum; k++) {
                        if (dp[j][k] > 0) {
                            for (int m = 1; m <= sames; m++) {
                                dp[j + m][k + m * w[i]] = Math.min(2, dp[j + m][k + m * w[i]] + dp[j][k]);
                            }
                        }
                    }
                }

                for (int j = 1; j <= sames; j++) {
                    dp[j][w[i] * j] = Math.min(2, dp[j][w[i] * j] + 1);
                }
                sames = 0;
            }

            int result = 0;
            sames = 0;
            for (int i = 1; i <= n; i++) {
                if (i > 1 && w[i] != w[i - 1]) {
                    sames = 0;
                }
                sames++;
                if (dp[sames][w[i] * sames] == 1) {
                    result = Math.max(result, sames);
                }
            }
            out.println(result);
        }

    }

    static class InputReader {
        private static BufferedReader in;
        private static StringTokenizer tok;

        public InputReader(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
        }

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

        public int[] read1BasedIntArray(int n) {
            int[] ar = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                ar[i] = nextInt();
            }
            return ar;
        }

        public String next() {
            try {
                while (tok == null || !tok.hasMoreTokens()) {
                    tok = new StringTokenizer(in.readLine());
                    //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
                }
            } catch (IOException ex) {
                System.err.println("An IOException was caught :" + ex.getMessage());
            }
            return tok.nextToken();
        }

    }
}


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;

public class B {

	static int N;
	static int ar[];
	static int dp[][][][];
	public static void main(String[] args) {
		JS in = new JS();
		N = in.nextInt();
		ar = new int[N];
		int cnt[] = new int[101];
		for(int i = 0; i < N; i++) {
			ar[i] = in.nextInt();
			cnt[ar[i]]++;
		}
		Arrays.sort(ar);

		dp = new int[101][101][101][101];
		for(int a[][][] : dp)
			for(int b[][] : a)
				for(int c[] : b)
					Arrays.fill(c, -1);
		int res = 0;
		for(int i = 0; i <= 100; i++) {
			for(int take = 1; take <= cnt[i]; take++) {
				int curSum = i*take;

				int val = go(0,curSum,take,i);
				if(val == 0) res = Math.max(res, take);
			}
		}
		System.out.println(res);
	}

	static int go(int id, int sum, int left, int num) {
		if(sum < 0) return 0;
		if(left == 0) {
			if(sum == 0) return 1;
			return 0;
		}
		if(id >= N) return 0;
		if(dp[id][sum][left][num] != -1) return dp[id][sum][left][num];

		int res = go(id+1,sum,left,num);
		if(ar[id] != num) {
			res = Math.max(res, go(id+1,sum-ar[id],left-1,num));
		}
		return dp[id][sum][left][num] = res;
	}

	static class JS{
		public int BS = 1<<16;
		public char NC = (char)0;
		byte[] buf = new byte[BS];
		int bId = 0, size = 0;
		char c = NC;
		double num = 1;
		BufferedInputStream in;

		public JS() {
			in = new BufferedInputStream(System.in, BS);
		}

		public JS(String s) throws FileNotFoundException {
			in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
		}

		public char nextChar(){
			while(bId==size) {
				try {
					size = in.read(buf);
				}catch(Exception e) {
					return NC;
				}
				if(size==-1)return NC;
				bId=0;
			}
			return (char)buf[bId++];
		}

		public int nextInt() {
			return (int)nextLong();
		}

		public long nextLong() {
			num=1;
			boolean neg = false;
			if(c==NC)c=nextChar();
			for(;(c<'0' || c>'9'); c = nextChar()) {
				if(c=='-')neg=true;
			}
			long res = 0;
			for(; c>='0' && c <='9'; c=nextChar()) {
				res = (res<<3)+(res<<1)+c-'0';
				num*=10;
			}
			return neg?-res:res;
		}

		public double nextDouble() {
		    while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar();
		    boolean neg = c=='-';
		    if(neg)c=nextChar();
		    boolean fl = c=='.';
		    double cur = nextLong();
		    if(fl) return neg ? -cur/num : cur/num;
		    if(c == '.') {
			double next = nextLong();
			return neg ? -cur-next/num : cur+next/num;
		    }
		    else return neg ? -cur : cur;
		}

		public String next() {
			StringBuilder res = new StringBuilder();
			while(c<=32)c=nextChar();
			while(c>32) {
				res.append(c);
				c=nextChar();
			}
			return res.toString();
		}

		public String nextLine() {
			StringBuilder res = new StringBuilder();
			while(c<=32)c=nextChar();
			while(c!='\n') {
				res.append(c);
				c=nextChar();
			}
			return res.toString();
		}

		public boolean hasNext() {
			if(c>32)return true;
			while(true) {
				c=nextChar();
				if(c==NC)return false;
				else if(c>32)return true;
			}
		}
	}

}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.Arrays;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		InputStream input;
		OutputStream output;
		try {
			input = new FileInputStream("input.txt");
			output = new FileOutputStream("output.txt");
		} catch (FileNotFoundException e) {
			input = System.in;
			output = System.out;
		}
		Kattio io = new Kattio(input, output);
		(new Solve(io)).main();
		io.close();

		if (input instanceof FileInputStream)
			try {
				input.close();
			} catch (IOException e) {
			}
		if (output instanceof FileOutputStream)
			try {
				output.close();
			} catch (IOException e) {
			}
	}

}

class Solve {
	static final long mod = (long) 1e9+7;
	Kattio io;
	int n;
	int[] a;
	long[][][] dp;
	int maxx;

	long[] fac;

	Solve(Kattio io) {
		this.io = io;
	}

	long pow(long x,long y)
	{
		if (y==0) return 1;
		else
		{
			long p=pow(x,y/2);
			p=p*p%mod;
			if (y%2==1) return p*x%mod;
			else return p;
		}
	}

	long nCk(int n,int k)
	{
		return fac[n]*pow(fac[k]*fac[n-k]%mod,mod-2)%mod;
	}

	long caldp(int x,int y,int z)
	{
//		if (dp[x][y][z]!=-1) return dp[x][y][z];
//
//		if (x==n && z==0 && y==0)
//			dp[x][y][z]=1;
//		else
//		if (x==n)
//			dp[x][y][z]=0;
//		else
//		{
//			dp[x][y][z]=caldp(x+1,y,z);
//			if (z>=a[x+1] && y>=1) dp[x][y][z]=(dp[x][y][z]+caldp(x+1,y-1,z-a[x+1]))%mod;
//		}
//
//		return dp[x][y][z];

		try
		{
			dp = new long[2][n+1][z+1];

			for (int i=n; i>=0; i--)
				for (int j=y; j>=0; j--)
					for (int k=z; k>=0; k--)
					{
						if (i==n && j==0 & k==0)
							dp[i%2][j][k]=1;
						else
						if (i==n)
							dp[i%2][j][k]=0;
						else
						{
							dp[i%2][j][k]=dp[(i+1)%2][j][k];
							if (j>=1 && k>=a[i+1]) dp[i%2][j][k]=(dp[i%2][j][k]+dp[(i+1)%2][j-1][k-a[i+1]])%mod;
						}
					}
		}
		catch (ArrayIndexOutOfBoundsException e)
		{
			io.println(x+" "+y+" "+z);
		}

		return dp[x][y][z];
	}

	void main()
	{
		n=io.getInt();
		a = new int[n+1];

		maxx = 0;
		TreeMap<Integer,Integer> S = new TreeMap<Integer,Integer>();

		for (int i=1; i<=n; i++)
		{
			a[i]=io.getInt();
			maxx+=a[i];
			if (S.containsKey(a[i]))
				S.put(a[i], S.get(a[i])+1);
			else
				S.put(a[i], 1);
		}

		if (S.size()==2)
		{
			io.print(n);
			return;
		}

		dp = new long[n+1][n+1][maxx+1];
		for (int i=0; i<=n; i++)
			for (int j=0; j<=n; j++)
				Arrays.fill(dp[i][j],-1);

		fac = new long[n+1];
		fac[0]= 1;
		for (int i=1; i<=n; i++)
			fac[i] = fac[i-1]*i%mod;

		int res=0;
		for (Map.Entry<Integer, Integer> entry: S.entrySet())
		{
			Integer value = entry.getValue();
			Integer key = entry.getKey();
			for (int i=res+1; i<=value; i++)
				if (caldp(0,i,key*i)==nCk(value,i))
					res=Math.max(res, i);
		}

		io.println(res);

	}
}

/** Simple yet moderately fast I/O routines.
*
* Example usage:
*
* Kattio io = new Kattio(System.in, System.out);
*
* while (io.hasMoreTokens()) {
*    int n = io.getInt();
*    double d = io.getDouble();
*    double ans = d*n;
*
*    io.println("Answer: " + ans);
* }
*
* io.close();
*
*
* Some notes:
*
* - When done, you should always do io.close() or io.flush() on the
*   Kattio-instance, otherwise, you may lose output.
*
* - The getInt(), getDouble(), and getLong() methods will throw an
*   exception if there is no more data in the input, so it is generally
*   a good idea to use hasMoreTokens() to check for end-of-file.
*
* @author: Kattis
*/
class Kattio extends PrintWriter {
	public Kattio(InputStream i) {
		super(new BufferedOutputStream(System.out));
		r = new BufferedReader(new InputStreamReader(i));
	}

	public Kattio(InputStream i, OutputStream o) {
		super(new BufferedOutputStream(o));
		r = new BufferedReader(new InputStreamReader(i));
	}

	public boolean hasMoreTokens() {
		return peekToken() != null;
	}

	public int getInt() {
		return Integer.parseInt(nextToken());
	}

	public double getDouble() {
		return Double.parseDouble(nextToken());
	}

	public long getLong() {
		return Long.parseLong(nextToken());
	}

	public String getWord() {
		return nextToken();
	}

	private BufferedReader r;
	private String line;
	private StringTokenizer st;
	private String token;

	private String peekToken() {
		if (token == null)
			try {
				while (st == null || !st.hasMoreTokens()) {
					line = r.readLine();
					if (line == null)
						return null;
					st = new StringTokenizer(line);
				}
				token = st.nextToken();
			} catch (IOException e) {
			}
		return token;
	}

	private String nextToken() {
		String ans = peekToken();
		token = null;
		return ans;
	}
}


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

public class B {

   static int[] memo;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); int m = sc.nextInt();
        // the question essentially asks how many answers we can find
        // for i^2 + j^2 divisible by m
//        memo = new int[m]; // array of count of residues
//        for (int i = 0; i < m; i++) {
//            memo[(i * i) % m]++;
//        }
        long total = 0; // we can store n^2 in long
        // n splits into n/m *m + n%m
        long bigSqTotal = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < m; j++) {
                bigSqTotal += ((i*i + j*j) % m == 0) ? 1 : 0;
            }
        }
        bigSqTotal *= (n/m);
        bigSqTotal *= (n/m); // big box
        total += bigSqTotal;

        long bigRectangleTotal = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 1; j <= n%m; j++) {
                bigRectangleTotal += ((i*i + j*j) % m == 0) ? 1 : 0;
            }
        }

        bigRectangleTotal *= (n/m);
        bigRectangleTotal *= 2;
        total += bigRectangleTotal;

        long smallSquareTotal = 0;
        for (int i = 1; i <= n%m; i++) {
            for (int j = 1; j <= n%m; j++) {
                smallSquareTotal += ((i*i + j*j) % m == 0) ? 1 : 0;
            }
        }

        total += smallSquareTotal;
        System.out.println(total);
    }

}


package com.company;

import java.util.Scanner;

public class Lab8 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        long m = scanner.nextLong();
        long amountOfPairs = 0;
        for (long x = 0; x < m; x++) {
            for (long y = 0; y < m; y++) {
                if ((x * x + y * y) % m == 0) {
                    long amountOfX = x > 0 ? ((n - x) / m + 1) : ((n - x) / m);
                    long amountOfY = y > 0 ? ((n - y) / m + 1) : ((n - y) / m);
                    amountOfPairs += amountOfX * amountOfY;
                }
            }
        }
        System.out.print(amountOfPairs);
    }

}


import java.util.Scanner;
public class nn {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long m = sc.nextLong();
        long ans = 0;
        for(int i = 1;i <= m;i++){
            for(int j = 1;j <= m;j++){
                long v = (i*i+j*j)%m;
                if(v == 0 ){
                    ans++;
                }
            }
        }
        System.out.println(ans);


import jdk.internal.util.xml.impl.Input;

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

public class Main {

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        int n = in.nextInt();
        int m = in.nextInt();
        long ans=0;
        for (int i =1;i<=Math.min(n,m);i++)
            for (int j =1;j<=Math.min(n,m);j++)
            {
                if ((i*i+j*j)%m==0)
                {
                    ans+=(long)((long)((n-i)/m+1)*((long)(n-j)/m+1));
                }
            }

            out.printLine(ans);
        out.flush();

    }
    static int binarySearch(int []arr,int n,int p)
    {

        int st = 0;
        int end = n-1;
        int mid = (st + end)/2;
        int temp = 0;
        while(st <= end)
        {
            mid = (st + end)/2;

            if(p >= arr[mid])
            {
                st = mid+1;

            }
            else if(p < arr[mid])
            {
                end = mid-1;

            }
            temp = st;

        }

        return temp;
    }
    static void MergeSort(int[] a, int[] b,  int p, int r)
    {
        if (p < r)
        {
            int q = (r + p) / 2;
            MergeSort(a, b,  p, q);
            MergeSort(a, b,  q + 1, r);
            Merge(a, b, p, q, r);
        }
    }
    static void Merge(int[] a, int[] b,int p, int q, int r)
    {
        int n1 = q - p + 1;
        int n2 = r - q;
        int[] R = new int[n1 + 1];
        int[] L = new int[n2 + 1];
        int[] R1 = new int[n1];
        int[] L1 = new int[n2];

        for (int i = 0; i < n1; i++)
        {
            R[i] = a[p + i];
            R1[i] = b[p + i];

        }
        R[n1] = Integer.MAX_VALUE;
        for (int i = 0; i < n2; i++)
        {
            L[i] = a[q + i + 1];
            L1[i] = b[q + i + 1];

        }
        L[n2] =Integer.MAX_VALUE;
        int n = a.length;
        int j = 0;
        int k = 0;
        for (int i = p; i <= r; i++)
        {
            if (L[j] < R[k])
            {
                a[i] = L[j];
                b[i] = L1[j];

                j++;
            }
            else if (L[j]>R[k])
            {
                a[i] = R[k];
                b[i] = R1[k];

                k++;
            }
            else
            {
                if (L1[j] < R1[k])
                {
                    a[i] = L[j];
                    b[i] = L1[j];

                    j++;
                }
                else
                {
                    a[i] = R[k];
                    b[i] = R1[k];

                    k++;
                }
            }

        }
    }
}

class pair  implements Comparable
{

    int key;
    int value;
    public pair(Object key, Object value) {

        this.key = (int)key;
        this.value=(int)value;
    }

    @Override
    public int compareTo(Object o) {
        pair temp =(pair)o;
        return  key-temp.key;
    }
}
class Graph {

    int n;
    ArrayList<Integer>[] adjList;

    public Graph(int n) {
        this.n = n;
        adjList = new ArrayList[n];
        for (int i = 0; i < n; i++)
            adjList[i] = new ArrayList<>();
    }

}

class InputReader {

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

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

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

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

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

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

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

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

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

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

}

class OutputWriter {
    private final PrintWriter writer;

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

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

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

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

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

}


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

public class C {
    private static StringTokenizer st;
    private static BufferedReader br;
    public static long MOD = 1000000007;

    public static void print(Object x) {
        System.out.println(x + "");
    }
    public static void printArr(long[] x) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < x.length; i++) {
            s.append(x[i] + " ");
        }
        print(s);
    }
    public static String join(List<?> x, String space) {
        StringBuilder sb = new StringBuilder();
        for (Object elt : x) {
            sb.append(elt);
            sb.append(space);
        }
        return sb.toString();
    }

    public static String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = br.readLine();
            st = new StringTokenizer(line.trim());
        }
        return st.nextToken();
    }
    public static int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public static long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public static List<Integer> nextInts(int N) throws IOException {
        List<Integer> ret = new ArrayList<Integer>();
        for (int i = 0; i < N; i++) {
            ret.add(nextInt() - 1);
        }
        return ret;
    }

    public static double atMost(int[] l, int[] r, int i, int c) {
        if (i >= r[c]) return 1;
        if (i < l[c]) return 0;
        return (i-l[c]+1) / ((double) (r[c]-l[c]+1));
    }

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));

        int MAX = 12;
        int n = nextInt();
        int[] l = new int[n];
        int[] r = new int[n];
        for (int i = 0; i < n; i++) {
            l[i] = nextInt();
            r[i] = nextInt();
        }

        double[] atMost = new double[MAX+1];
        for (int i = 0; i <= MAX; i++) {
            double prob = 1;
            for (int c = 0; c < n; c++) {
                prob *= atMost(l, r, i, c);
            }
            atMost[i] = prob;
            for (int c = 0; c < n; c++) {
                double moreProb = 1;
                for (int c2 = 0; c2 < n; c2++) {
                    if (c == c2) continue;
                    moreProb *= atMost(l, r, i, c2);
                }
                moreProb *= 1 - atMost(l, r, i, c);
                atMost[i] += moreProb;
            }
        }

        double expected = 0;
        for (int i = 1; i <= MAX; i++) {
            expected += i * (atMost[i] - atMost[i-1]);
        }
        System.out.printf("%.15f%n", expected);
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class C {

    static int n;
    static long[] l;
    static long[] r;
    static double numerator = 0;
    static int second;
    static int[] mask;
    static boolean[] visited = new boolean[10];

    static long count(long l1, long r1, long l2, long r2) {
        l1 = Math.max(l1, l2);
        r1 = Math.min(r1, r2);
        return l1 <= r1 ? (r1 - l1 + 1) : 0;
    }

    static void dfs(int t, int greater, int equal) {
        if (greater > 1)
            return;
        if (t >= n) {
            if (equal == 0)
                return;
            if (greater == 0 && equal == 1)
                return;

            long cnt = 1;
            for (int i = 0; i < n; i++) {
                if (mask[i] > 0) {
                    cnt *= count(l[i], r[i], second + 1, Integer.MAX_VALUE);
                } else if (mask[i] == 0) {
                    cnt *= count(l[i], r[i], second, second);
                } else {
                    cnt *= count(l[i], r[i], 0, second - 1);
                }
            }
            numerator += second * cnt;
            //            if (cnt > 0)
            //                System.out.println(second + " " + Arrays.toString(mask) + " " + cnt);
        } else {
            mask[t] = 1;
            dfs(t + 1, greater + 1, equal);

            mask[t] = 0;
            dfs(t + 1, greater, equal + 1);

            mask[t] = -1;
            dfs(t + 1, greater, equal);
        }
    }

    public static void main(String[] args) throws Exception {
        Reader.init(System.in);
        BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));

        n = Reader.nextInt();
        l = new long[n];
        r = new long[n];
        long total = 1;
        for (int i = 0; i < n; i++) {
            l[i] = Reader.nextInt();
            r[i] = Reader.nextInt();
            total *= (r[i] - l[i] + 1);
        }

        mask = new int[n];
        for (second = 1; second <= 10000; second++) {
            dfs(0, 0, 0);
        }

        System.out.printf("%.10f%n", numerator / total);
        cout.close();
    }

    static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
        final U _1;
        final V _2;

        private Pair(U key, V val) {
            this._1 = key;
            this._2 = val;
        }

        public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
            return new Pair<U, V>(_1, _2);
        }

        @Override
        public String toString() {
            return _1 + " " + _2;
        }

        @Override
        public int hashCode() {
            int res = 17;
            res = res * 31 + _1.hashCode();
            res = res * 31 + _2.hashCode();
            return res;
        }

        @Override
        public int compareTo(Pair<U, V> that) {
            int res = this._1.compareTo(that._1);
            if (res < 0 || res > 0)
                return res;
            else
                return this._2.compareTo(that._2);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (!(obj instanceof Pair))
                return false;
            Pair<?, ?> that = (Pair<?, ?>) obj;
            return _1.equals(that._1) && _2.equals(that._2);
        }
    }

    /** Class for buffered reading int and double values */
    static class Reader {
        static BufferedReader reader;
        static StringTokenizer tokenizer;

        /** call this method to initialize reader for InputStream */
        static void init(InputStream input) {
            reader = new BufferedReader(new InputStreamReader(input));
            tokenizer = new StringTokenizer("");
        }

        /** get next word */
        static String next() throws IOException {
            while (!tokenizer.hasMoreTokens()) {
                // TODO add check for eof if necessary
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }

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

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

    static class ArrayUtil {
        static void swap(int[] a, int i, int j) {
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        static void swap(long[] a, int i, int j) {
            long tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        static void swap(double[] a, int i, int j) {
            double tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        static void swap(char[] a, int i, int j) {
            char tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        static void swap(boolean[] a, int i, int j) {
            boolean tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        static void reverse(int[] a, int i, int j) {
            for (; i < j; i++, j--)
                swap(a, i, j);
        }

        static void reverse(long[] a, int i, int j) {
            for (; i < j; i++, j--)
                swap(a, i, j);
        }

        static void reverse(double[] a, int i, int j) {
            for (; i < j; i++, j--)
                swap(a, i, j);
        }

        static void reverse(char[] a, int i, int j) {
            for (; i < j; i++, j--)
                swap(a, i, j);
        }

        static void reverse(boolean[] a, int i, int j) {
            for (; i < j; i++, j--)
                swap(a, i, j);
        }

        static long sum(int[] a) {
            int sum = 0;
            for (int i : a)
                sum += i;
            return sum;
        }

        static long sum(long[] a) {
            long sum = 0;
            for (long i : a)
                sum += i;
            return sum;
        }

        static double sum(double[] a) {
            double sum = 0;
            for (double i : a)
                sum += i;
            return sum;
        }

        static int max(int[] a) {
            int max = Integer.MIN_VALUE;
            for (int i : a)
                if (i > max)
                    max = i;
            return max;
        }

        static int min(int[] a) {
            int min = Integer.MAX_VALUE;
            for (int i : a)
                if (i < min)
                    min = i;
            return min;
        }

        static long max(long[] a) {
            long max = Long.MIN_VALUE;
            for (long i : a)
                if (i > max)
                    max = i;
            return max;
        }

        static long min(long[] a) {
            long min = Long.MAX_VALUE;
            for (long i : a)
                if (i < min)
                    min = i;
            return min;
        }
    }
}


import java.util.*;

/**
 * Created by aonuchin on 07.02.15.
 */
public class A {
    static class Range {
        int fromInc;
        int toInc;

        public Range(int fromInc, int toInc) {
            this.fromInc = fromInc;
            this.toInc = toInc;
        }

        Integer fromInc() {
            return fromInc;
        }

        boolean in(int number) {
            return fromInc <= number && number <= toInc;
        }
    }
    public static void main(String ... a) {
        Scanner input = new Scanner(System.in);
        int companies = input.nextInt();
        List<Range> ranges = new ArrayList<>();
        for (int i = 0; i < companies; i++) {
            ranges.add(new Range(input.nextInt(), input.nextInt()));
        }
        Collections.sort(ranges, Comparator.comparing(Range::fromInc));
        double expected = 0;
        int currentPrice = ranges.get(0).fromInc;
        for (Range range : ranges) {
            for (; currentPrice <= range.toInc; currentPrice++) {
                if (currentPrice < range.fromInc) {
                    currentPrice = range.fromInc;
                }
                double probability = calculateProbability(currentPrice, ranges);
                assert probability <= 1.0;
                expected += probability * currentPrice;
            }
        }
        System.out.println(expected);
    }

    private static double calculateProbability(int currentPrice, List<Range> ranges) {
        double probability = 0;
        for (int firstPlace = 0 ; firstPlace < ranges.size(); firstPlace++) {
            for (int secondPlace = 0; secondPlace < ranges.size(); secondPlace++) {
                double p = probability(currentPrice, ranges, firstPlace, secondPlace);
                if (p > 0.0) {
                    probability += p;
                }
            }
        }
        return probability;
    }

    private static double probability(int currentPrice, List<Range> ranges, int firstPlace, int secondPlace) {
        if (firstPlace == secondPlace) {
            return - 10.0;
        }
        Range firstRange = ranges.get(firstPlace);
        Range secondRange = ranges.get(secondPlace);
        if (firstRange.toInc < currentPrice || !secondRange.in(currentPrice)) {
            return - 10.0;
        }

        double firstPlaceP = (firstRange.toInc - currentPrice) / (firstRange.toInc - firstRange.fromInc + 1.);
        if (firstRange.fromInc > currentPrice) {
            firstPlaceP = 1.;
        }
        double secondPlaceP = 1. / (secondRange.toInc - secondRange.fromInc + 1.);
        double otherP = 1.0;
        double otherAdd = 0.;
        double eq = 0.;
        for (int otherPlace = 0 ; otherPlace < ranges.size(); otherPlace++) {
            if (otherPlace == firstPlace || otherPlace == secondPlace) {
                continue;
            }
            Range otherRange = ranges.get(otherPlace);
            if (currentPrice < otherRange.fromInc) {
                return  -10.0;
            }
            if (currentPrice > otherRange.toInc) {
                continue;
            }

            otherP = otherP * ((currentPrice - otherRange.fromInc) / (otherRange.toInc - otherRange.fromInc + 1.));
            if (otherPlace < secondPlace) {
                otherAdd += 1./ (otherRange.toInc - otherRange.fromInc + 1.);
            }
            if (otherPlace < firstPlace && firstPlace < secondPlace) {
                eq += 1./ (otherRange.toInc - otherRange.fromInc + 1.);
            }
        }
        double firstAddP = 0.;
        if (firstPlace < secondPlace) {
            firstAddP = 1.  / (firstRange.toInc - firstRange.fromInc + 1.) ;
        }
        return firstPlaceP  * secondPlaceP * (otherP + otherAdd)  +
                (eq + otherP) * firstAddP * secondPlaceP;
    }
}


import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Prob03 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] L = new int[N];
        int[] R = new int[N];
        for (int i = 0; i < N; i++) {
            L[i] = in.nextInt();
            R[i] = in.nextInt();
        }
        double[] probabilities = new double[11];
        for (int i = 0; i < N; i++) {
            for (int j = L[i]; j <= R[i]; j++) {
                double prob = 1./(R[i]-L[i]+1);
                //count probability j to be the second largest
                double probResult = 0;
                outer:
                for (int k = 0; k < N; k++) {
                    if (i == k) continue;

                    double probMax = (1.*R[k] - j)/(R[k]-L[k]+1);
                    if (probMax < 0) continue;
                    if (i < k && L[k]<=j && R[k] >= j)  probMax += 1./(R[k]-L[k]+1);
                    if (probMax > 1) probMax = 1;

                    for (int m = 0; m < N; m++) {
                        if (m==i || m == k) continue;
                        double probMin = (1.*j - L[m])/(R[m]-L[m]+1);
                        if (probMin < 0) continue outer;
                        if (m < i && L[m]<=j && R[m] >= j)  probMin += 1./(R[m]-L[m]+1);
                        if (probMin > 1) probMin = 1;
//                        System.out.println("second: " + j + " max prob: " + probMax + " min prob: " + probMin);
                        probMax *= probMin;
                    }
                    probResult += probMax;
                }
                prob *= probResult;
                probabilities[j] += prob;
//                System.out.println(Arrays.toString(probabilities));
            }
        }

        double sum = 0;
        double prob = 0;
        for (int i = 1; i < 11; i++) {
            sum += i *probabilities[i];
            prob += probabilities[i];
        }
//        System.out.println(sum);
//        System.out.println(sum / prob);
        System.out.println(String.format("%.9f", sum));
    }

}


/**
 * Created by underestimatedcoder on 2018-01-16.
 */
public class Garden {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int noOfBuckets = scanner.nextInt();
        int gardenLength = scanner.nextInt();
        scanner.nextLine();
        int tmp = 1000000000;
        for(int i = 0; i < noOfBuckets; i ++){
            int curr = scanner.nextInt();
            if(gardenLength % curr == 0 && tmp > gardenLength/curr){
                tmp =  gardenLength/curr;
            }
        }
        System.out.println(tmp);

    }

}


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

public class scorify{
	public static void main(String[] args){
	Scanner in=new Scanner(System.in);
    int n = in.nextInt(),min;
    int len = in.nextInt();
    int[] arr = new int[n];
    TreeSet<Integer> set = new TreeSet<Integer>();

    for (int i =0; i<n ; i++){
        min = 0;
        arr[i]=in.nextInt();
        while(min != len){
            min += arr[i];
            seconds++;
            if(min>len){seconds+=1000;break;}
        }
        set.add(seconds);
    }
    System.out.println(set.first());

	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {

	final static int mod = 1_000_000_007;

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

		STDIN scan = new STDIN();
		StringBuilder sb = new StringBuilder();

		int n = scan.nextInt(), k = scan.nextInt(), ans = Integer.MAX_VALUE;
		for(int i = 0; i < n; i++) {
			int curr = scan.nextInt();
			if(k % curr == 0) ans = Math.min(ans, k / curr);
		}
		sb.append(ans)

		System.out.println(sb);

	}

	static class STDIN {
		BufferedReader br;
		StringTokenizer st;

		public STDIN() {
			br = new BufferedReader(new InputStreamReader(System.in));
			st = null;
		}

		boolean hasNext() throws Exception {
			if (!st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.hasMoreTokens();
		}

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

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

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

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

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


import org.aspectj.util.GenericSignature;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Garden {
    Scanner sc = new Scanner(System.in);
    int bucket = sc.nextInt();
    int gardenSize = sc.nextInt();
    ArrayList<Integer> buckets = new ArrayList<>();

    public static void main(String[] args) {
        System.out.println(new Garden().otvet());
    }

    public int otvet(){
        for(int i = 0; i < bucket; i++){
            int temp = sc.nextInt();
            if(gardenSize%temp == 0) buckets.add(temp);
        }
        Collections.sort(buckets);
        return gardenSize/buckets.get(buckets.size()-1);
    }
}


import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main( String[] args ) throws java.lang.Exception {

        java.io.BufferedReader r = new java.io.BufferedReader( new java.io.InputStreamReader( System.in ) );

        String[] tokens = r.readLine().split( " " );

        List<Integer> towerOne = new ArrayList<>();
        List<Integer> towerTwo = new ArrayList<>();

        int max = Math.max( Integer.parseInt( tokens[0] ), Integer.parseInt( tokens[1] ) );
        int min = Math.min( Integer.parseInt( tokens[1] ), Integer.parseInt( tokens[0] ) );

        max = max == 0 ? 1 : max;
        min = min == 0 ? 1 : min;

        if ( (max / min) > min ) {
            if (max == Integer.parseInt( tokens[0] )) {
                System.out.println( max * 2 );
            } else {
                System.out.println( max * 3 );
            }

            return;
        }

        for( int i = 0; i < Integer.parseInt( tokens[0] ); i++ ) {
            towerOne.add( (i + 1) * 2 );
        }

        for( int i = 0; i < Integer.parseInt( tokens[1] ); i++ ) {
            towerTwo.add( (i + 1) * 3 );
        }

        for (int i = 1 ; i <= max( towerOne, towerTwo ); i++){
            if ( towerOne.contains( i ) && towerTwo.contains( i ) ){
                if ( height(towerOne) + 2 > height( towerTwo ) + 3 ){
                    towerTwo.add( height( towerTwo ) + 3 );
                } else {
                    towerOne.add( height( towerOne ) + 2 );
                }
            }

            if (towerOne.size() >1 && towerOne.indexOf( i ) != -1) {
                towerOne.remove( towerOne.indexOf( i ) );
            }
            if (towerTwo.size() >1 && towerTwo.indexOf( i )!= -1) {
                towerTwo.remove( towerTwo.indexOf( i ) );
            }
        }

        System.out.println( max( towerOne, towerTwo ) );
    }

    private static Integer max(List<Integer> l1, List<Integer> l2){
        if ( l1.size() == 0 ) return l2.get( l2.size() - 1 );
        if ( l2.size() == 0 ) return l1.get( l1.size() - 1 );

        return Math.max( l2.get( l2.size() - 1 ), l1.get( l1.size() - 1 ) );
    }

    private static Integer height(List<Integer> l){
        if (l.size() == 0) {
            return 0;
        } else {
            return l.get( l.size() - 1 );
        }
    }

}


import java.util.ArrayList;
import java.util.Scanner;

public class blockTowers {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan=new Scanner(System.in);
		long two=scan.nextLong();
		long three=scan.nextLong();
		if(two==0){
			System.out.println(three*3);
			return;
		}
		if(three==0){
			System.out.println(two*2);
			return;
		}
		ArrayList<Long> twos=new ArrayList<Long>();
		ArrayList<Long> threes=new ArrayList<Long>();
		for(long i=1;i<=two;i++){
			twos.add(2*i);
		}
		for(long i=1;i<=three;i++){
			threes.add(3*i);
		}
		long c=unique(twos,threes);
		while(c!=-1){
			if(twos.get(twos.size()-1)+2>threes.get(threes.size()-1)+3){
				int start=threes.indexOf(c);
				for(int i=start;i<threes.size();i++){
					threes.set(i, threes.get(i)+3);
				}

			}else{
				long start=twos.indexOf(c);
				for(long i=start;i<twos.size();i++){
					twos.set((int) i, twos.get((int) i)+2);
				}

			}
			c=unique(twos,threes);
		}
		System.out.println(Math.max(twos.get(twos.size()-1), threes.get(threes.size()-1)));

	}
	static long unique(ArrayList<Long> a,ArrayList<Long> b){
		long c=6;
		if(a.size()==0||b.size()==0)return -1;
		while(true){
			if(a.get(a.size()-1)<c||b.get(b.size()-1)<c){
				return -1;
			}
			if(a.contains(c)&&b.contains(c)){
				return c;
			}
			c+=6;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.BitSet;

public class blocktowers {

    public static void main(String[] args) throws Exception {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter w = new PrintWriter(System.out);

        String[] inputs = r.readLine().split(" ");
        int two = Integer.parseInt(inputs[0]);
        int three = Integer.parseInt(inputs[1]);

        //always use 2's to make room for the smallest number of 3s
        /*
        int min2 = two * 2;
        int min3 = three * 3;

        //CustomBitSet chosen = new CustomBitSet();

        long answer = 0;
        if (min2 > min3) {
            //accomodate for min2, when choosing from potential 3's always skip the multiples of 2

            long mult2 = 0;
            long mult3 = 0;

            for (int i = 0; i < three; i++) {
                mult3 += 3;
                if (mult3 % 2 == 0 && mult3 <= min2) mult3 += 3;
                //chosen.set(mult3);
            }

            mult2 = min2;

            answer = Math.max(mult3, mult2);
        } else if (min2 <= min3) {
            //accomodate for min3, when choosing form potential 2's always skip them ultibles of 3
            long mult2 = 0;
            long mult3 = 0;

            for (int i = 0; i < two; i++) {
                mult2 += 2;
                if (mult2 % 3 == 0 && mult2 <= min3) mult2 += 2;
            }

            mult3 = min3;

            answer = Math.max(mult3, mult2);
        }

        w.println(answer);
        w.close();
        */

        int twoHighest = 2;
        int threeHighest = 3;
        two--;
        three--;
        long min2 = two * 2;
        long min3 = three * 3;

        BitSet chosen = new BitSet();

        while (two > 0 || three > 0) {
            //find the one that results in the lower sum

            min2 = twoHighest + two * 2;
            min3 = threeHighest + three * 3;
            if ((twoHighest + 2) % 3 == 0 && two > 0 && three > 0) {
                //check if min2 or min3 is greater
                if (min2 < min3) {
                    //increase 4
                    twoHighest += 4;
                    two-=2;
                    if (chosen.get(twoHighest)) {
                        twoHighest += 2;
                        two--;
                    }
                    chosen.set(twoHighest);
                }
            } else if (two > 0) {
                twoHighest += 2;
                two--;
                if (chosen.get(twoHighest)) {
                    twoHighest += 2;
                    two--;
                }
                chosen.set(twoHighest);
            }

            if ((threeHighest + 3) % 2 == 0 && three > 0 && two > 0) {
                if (min2 > min3) {
                    //increase 6
                    threeHighest += 6;
                    three-=2;
                    if (chosen.get(threeHighest)) {
                        threeHighest += 3;
                        three--;
                    }
                    chosen.set(threeHighest);
                }
            } else if (three > 0) {
                threeHighest += 3;
                three--;
                if (chosen.get(threeHighest)) {
                    threeHighest += 3;
                    three--;
                }
                chosen.set(threeHighest);
            }
        }

        w.println(Math.max(twoHighest, threeHighest));
        w.close();
    }
    /*
    public static class CustomBitSet {
        //Use 3 bitsets
        BitSet one = new BitSet(2000000000);
        BitSet two = new BitSet(2000000000);
        //BitSet three = new BitSet(1000000000);

        public void set(long number) {
            //check if it's in 1 or 2 or 3

            if (number >= 4000000000L) {
                //third set
                //three.set((int) (number - 4000000000L));
            } else if (number >= 2000000000) {
                two.set((int) (number - 2000000000));
            } else {
                one.set((int) number);
            }
        }

        public boolean get(long number) {
            if (number >= 4000000000L) {
                //third set
                //return three.get((int) (number - 4000000000L));
                return false;
            } else if (number >= 2000000000) {
                return two.get((int) (number - 2000000000));
            } else {
                return one.get((int) number);
            }
        }
    }*/

}


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

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

    static class TaskC {
        private int calcMtop(int M, int evens) {
            int top = M * 3;
            int gaps = M / 2 - evens;

            if (gaps == 0)
                return top;

            if (M % 2 == 0) {
                top += 3;
            } else {
                top += 6;
            }
            gaps--;

            top += 6 * gaps;

            return top;
        }

        private int calcNtop(int N, int evens) {
            int top = N * 2;

            for (int i = 0; i < evens; i++) {
                if ((i + 1) * 6 <= top)
                    top += 2;
            }

            return top;
        }

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int N = in.nextInt();
            int M = in.nextInt();

            int evens = M / 2;

            int mtop = calcMtop(M, evens);
            int ntop = calcNtop(N, evens);

            int result = Math.max(mtop, ntop);

            while (evens > 0) {
                evens--;
                mtop = calcMtop(M, evens);
                ntop = calcNtop(N, evens);

                if (Math.max(mtop, ntop) < result)
                    result = Math.max(mtop, ntop);
                else
                    break;
            }

            out.println(result);

        }

    }
}


import java.util.*;
public class e {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		long n = input.nextLong() + 1, t = input.nextLong();

		boolean valid = false;
		long a = 1;
		int k = 1;
		for(int i = 0 ; i < 63; i++){
			if(t == a){
				valid = true;
				break;
			}
			a = a << 1;
			k++;
		}
		//System.out.println(k);
		if(!valid){
			System.out.println(0);
			return;
		}
		long sum = 0;
		int b = Long.bitCount(n);
		for(int i = 0; i < 63; i++)
			if(((1l << i) & n) != 0){
				//System.out.print(sum + " (" + i + ", " + (k - b + 1) + ")-->");
				sum += choose(i , k - b + 1);
				//System.out.println(sum);
				b--;
			}

		System.out.println(sum);
	}

	static long choose(int n, int k){
		if(k > n || k < 0)
			return 0;
		long ret = 1;
		for(int i = 1; i <= k; i++){
			ret *= n--;
			ret /= i;
		}
		return ret;
	}
}
/*
1000000000000 549755813888

*/


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Locale;
import java.util.InputMismatchException;
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
 * @author Jacob Jiang
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    long[][] C = NumberUtils.generateBinomialCoefficients(50, Long.MAX_VALUE);
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        long n = in.nextLong();
        long t = in.nextLong();
        int x = Long.numberOfTrailingZeros(t);
        if (t != (1l << x)) {
            out.println(0);
            return;
        }
        x++;
        long answer = 0;
        n++;
        while (n > 0) {
            long cur = Long.highestOneBit(n);
            n -= cur;
            answer += C[Long.numberOfTrailingZeros(cur)][x];
            x--;

        }
        out.println(answer);
    }
}

class NumberUtils {

    public static long[][] generateBinomialCoefficients(int n, long module) {
        long[][] result = new long[n + 1][n + 1];
        if (module == 1)
            return result;
        for (int i = 0; i <= n; i++) {
            result[i][0] = 1;
            for (int j = 1; j <= i; j++) {
                result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
                if (result[i][j] >= module)
                    result[i][j] -= module;
            }
        }
        return result;
    }

}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1 << 16];
    private int curChar;
    private int numChars;

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

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

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

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

    }

class OutputWriter {
    private PrintWriter writer;

    public OutputWriter(OutputStream stream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
    }

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

    public void println(long x) {
        writer.println(x);
    }

    public void println(int i) {
        writer.println(i);
    }

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

    }


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.BitSet;

public class ProblemC {

	static void doit(int m) {
		long[][] a = generate(m);
		int len = a.length;
		int c = 0;
		for (int j = 0 ; j < len ; j++) {
			c += a[len-1][j];
		}
		debug(m, c);
	}

	public static void main(String[] args) throws IOException {
		BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		String[] line = s.readLine().split(" ");
		long n = Long.valueOf(line[0]);
		long t = Long.valueOf(line[1]);

		int fc = -1;
		for (int f = 0 ; f < 60 ; f++) {
			if (Math.pow(2L, f) == t) {
				fc = f;
				break;
			}
		}
		if (fc == -1) {
			out.println(0);
			out.flush();
			return;
		}
		fc++;

		int len = 0;
		long nn = n;
		int[] bit = new int[128];
		while (nn >= 1) {
			bit[len] = (int)(nn % 2);
			nn /= 2L;
			len++;
		}

		long[][][] dp = new long[len+1][fc+1][3];
		dp[0][fc][0] = 1;
		for (int i = 0 ; i < len ; i++) {
			for (int f = 0 ; f <= fc ; f++) {
				for (int c = 0 ; c <= 2 ; c++) {
					if (dp[i][f][c] == 0) {
						continue;
					}
					long base = dp[i][f][c];
					if (bit[i] == 0) {
						// use one
						if (f >= 1) {
							dp[i+1][f-1][1] += base;
						}

						// use zero
						dp[i+1][f][c] += base;
					} else {
						// use one
						if (f >= 1) {
							dp[i+1][f-1][c] += base;
						}

						// use zero
						dp[i+1][f][2] += base;
					}
				}
			}
		}

		long ans = dp[len][0][2] + dp[len][0][0];
		out.println(ans);
		out.flush();
	}

	public static long[][] generate(int m ){
		long[][] a = new long[m+2][m+2];
		a[1][m+1] = 1;
		for (int i = 2 ; i <= m + 1 ; i++) {
			for (int j = 1 ; j <= m + 1 ; j++) {
				if (j == 1) {
					a[i][j] = a[i-1][j+1];
				} else {
					if (j == m + 1) {
						a[i][j] = a[i-1][j-1];
					} else {
						a[i][j] = a[i-1][j-1] ^ a[i-1][j+1];
					}
				}
			}
		}
		return a;
	}

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


//package codeforces.contests.cf160;

import java.io.*;

public class ProblemC {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    int[] readInts() throws IOException {
        String[] strings = reader.readLine().split(" ");
        int[] ints = new int[strings.length];
        for(int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(strings[i]);
        }
        return ints;
    }

    long[] readLongs() throws IOException {
        String[] strings = reader.readLine().split(" ");
        long[] longs = new long[strings.length];
        for(int i = 0; i < longs.length; i++) {
            longs[i] = Long.parseLong(strings[i]);
        }
        return longs;
    }

    long[][] dp = new long[64][64];
    boolean[][] vis = new boolean[64][64];

    long rec(long rows, long sum) {
        int br = bit(rows + 1);
        int bs = bit(sum);
        boolean ok = bits(rows + 1) == 1;
        if(ok) {
            if(vis[br][bs]) {
                return dp[br][bs];
            }
            vis[br][bs] = true;
        }
        if(sum == 1) {
            long ret = 0;
            for(long i = 1; i <= rows; i <<= 1) {
                ret++;
            }
            if(ok) {
                dp[br][bs] = ret;
            }
            return ret;
        }
        long ret = 0;
        for(long i = 1; ; i <<= 1) {
            if(i <= rows) {
                rows -= i;
                ret += rec(i - 1, sum / 2);
            }
            else {
                ret += rec(rows - 1, sum / 2);
                break;
            }
        }
        if(ok) {
            dp[br][bs] = ret;
        }
        return ret;
    }

    int bits(long n) {
        int b = 0;
        for(int i = 0; i < 64; i++) {
            if((n >> i) % 2 == 1) b++;
        }
        return b;
    }
    int bit(long n) {
        for(int i = 0; i < 60; i++) {
            if((1L << i) == n) return i;
        }
        return 61;
    }

    void solve() throws IOException {
        long[] tt = readLongs();
        long n = tt[0];
        long t = tt[1];
        if(bits(t) != 1) {
            writer.println(0);
        }
        else {
            writer.println(rec(n, t));
        }
        writer.flush();
    }

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


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

public class E {
	public static void main(String[] args) {
		MyScanner scan = new MyScanner();
		int N = scan.nextInt()-1;
		String s1 = scan.nextLine();
		String sTemp = scan.nextLine();
		if(N==1){
			if((s1.charAt(0)=='N'&&sTemp.charAt(0)=='S')||(s1.charAt(0)=='S'&&sTemp.charAt(0)=='N')){
				System.out.println("NO");
			}else if((s1.charAt(0)=='W'&&sTemp.charAt(0)=='E')||(s1.charAt(0)=='E'&&sTemp.charAt(0)=='W')){
				System.out.println("NO");
			}
			else{
				System.out.println("YES");
			}
			return;
		}

		String card = "EWSN";
		StringBuilder s2 = new StringBuilder("");
		for(int i=N-1;i>=0;i--){
			s2.append(card.charAt(card.indexOf(sTemp.charAt(i))^1));
		}

		String s = s2.toString();

		boolean valid = true;
		for(int i=1;i<=s.length();i++){
			if(s.substring(0, i).equals(s1.substring(s1.length()-i, s1.length()))){
				valid=false;
				break;
			}
		}
		System.out.println(valid?"YES":"NO");
	}
	private static class MyScanner {
	    BufferedReader br;
	    StringTokenizer st;

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

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

	    String nextLine(){
	          String str = "";
		  try {
		     str = br.readLine();
		  } catch (IOException e) {
		     e.printStackTrace();
		  }
		  return str;
	     }
	    int nextInt() {
	        return Integer.parseInt(next());
	    }
	 }
}


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

public class Marbles2 {

    public static void main(String[] args) {
        InReader sc = new InReader(System.in);
        int n = sc.nextInt() - 1;
        String a = sc.next();
        String b = sc.next();

        String brev = reverse(b);

        boolean no = false;
        out:
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i; j < n; j++) {
                if (a.charAt(j) != brev.charAt(j-i)) {
                    continue out;
                }
            }
            no = true;
            break;
        }
        if (no) {
            System.out.printf("NO");
        } else {
            System.out.println("YES");
        }

    }

    private static String reverse(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            char rc;
            switch (c) {
                case 'W':
                    rc = 'E';
                    break;
                case 'E':
                    rc = 'W';
                    break;
                case 'N':
                    rc = 'S';
                    break;
                case 'S':
                    rc = 'N';
                    break;
                default:
                    throw new AssertionError("Wrong char: " + c + ", at " + i);
            }
            sb.append(rc);
        }
        return sb.toString();
    }

    static class InReader {

        private BufferedReader br;
        private String[] split;
        private int index;

        public InReader(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in), 1024 * 1024);
        }

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

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

        public String next() {
            try {
                while (split == null || split.length <= index) {
                    String line = br.readLine();
                    if (line != null && !line.isEmpty()) {
                        split = line.split(" ");
                        index = 0;
                    }
                }
                return split[index++];
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

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

        public int[][] getPairArray(int n) {
            int[][] res = new int[2][n];
            for (int i = 0; i < n; i++) {
                res[0][i] = nextInt();
                res[1][i] = nextInt();
            }
            return res;
        }

    }
}