import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class Techno19_2F {
	static final Comparator<int[]> COMP_ARR = new Comparator<int[]>() {
		public int compare(int[] a1, int[] a2) {
			if (a1.length < a2.length) {
				return -1;
			}
			if (a1.length > a2.length) {
				return 1;
			}

			for (int i = 0; i < a1.length; i++) {
				if (a1[i] < a2[i]) {
					return -1;
				}
				if (a1[i] > a2[i]) {
					return 1;
				}
			}
			return 0;
		}
	};

	static TreeMap<int[], Integer> index = new TreeMap<>(COMP_ARR);
	static ArrayList<int[]> start = new ArrayList<>();

	static int[] numD;

	static int[] pFact = new int[1_000_001];

	public static void main(String[] args) throws IOException {
		cGen = new int[23];
		numD = new int[6000];
		genAll(0, 23, 23, 1);
		genStart(0, 20, 20, 1);

		divCost = new int[start.size()][301];
		for (int[] a : divCost) {
			Arrays.fill(a, Integer.MAX_VALUE / 2);
		}
		cost = new int[index.size()];

		Collections.sort(start, COMP_ARR);
		for (int i = 0; i < start.size(); i++) {
			bfs(start.get(i), i);
		}

		Arrays.fill(pFact, 1);
		for (int i = 2; i <= 1_000_000; i++) {
			if (pFact[i] == 1) {
				for (int m = i; m <= 1_000_000; m += i) {
					pFact[m] = i;
				}
			}
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

		int nT = Integer.parseInt(reader.readLine());

		while (nT-- > 0) {
			StringTokenizer inputData = new StringTokenizer(reader.readLine());
			int a = Integer.parseInt(inputData.nextToken());
			int b = Integer.parseInt(inputData.nextToken());

			int[] aA = toArray(a);
			int[] bA = toArray(b);

			int aSI = Collections.binarySearch(start, aA, COMP_ARR);
			int bSI = Collections.binarySearch(start, bA, COMP_ARR);

			int minA = Integer.MAX_VALUE / 4;
			for (int nD = 1; nD <= 300; nD++) {
				minA = Math.min(minA, divCost[aSI][nD] + divCost[bSI][nD]);
			}
			printer.println(minA);
		}
		printer.close();
	}

	static int[] toArray(int a) {
		ArrayList<Integer> cnts = new ArrayList<Integer>();
		int last = -1;
		int cCnt = 0;

		while (a > 1) {
			int cPFact = pFact[a];
			if (cPFact == last) {
				cCnt++;
			} else {
				if (cCnt != 0) {
					cnts.add(cCnt);
				}
				last = cPFact;
				cCnt = 1;
			}
			a /= pFact[a];
		}
		if (cCnt != 0) {
			cnts.add(cCnt);
		}
		Collections.sort(cnts, Comparator.reverseOrder());
		int[] res = new int[cnts.size()];
		for (int i = 0; i < cnts.size(); i++) {
			res[i] = cnts.get(i);
		}
		return res;
	}

	static int[] cost;

	static int[][] divCost;

	static void bfs(int[] sState, int searchI) {
		int sInd = index.get(sState);
		ArrayDeque<int[]> states = new ArrayDeque<>();
		ArrayDeque<Integer> stInds = new ArrayDeque<>();

		states.add(sState);
		stInds.add(index.get(sState));

		Arrays.fill(cost, -1);
		cost[sInd] = 0;

		while (!states.isEmpty()) {
			int[] cState = states.remove();
			int cStInd = stInds.remove();

			for (int i = 0; i < cState.length; i++) {
				if (i == 0 || cState[i - 1] > cState[i]) {
					int[] nState = Arrays.copyOf(cState, cState.length);
					nState[i]++;

					Integer nStInd = index.get(nState);
					if (nStInd == null) {
						continue;
					}
					if (cost[nStInd] == -1) {
						cost[nStInd] = cost[cStInd] + 1;
						states.add(nState);
						stInds.add(nStInd);
					}
				}

				if (i == cState.length - 1) {
					if (cState[i] == 1) {
						int[] nState = Arrays.copyOf(cState, cState.length - 1);
						Integer nStInd = index.get(nState);
						if (nStInd == null) {
							continue;
						}
						if (cost[nStInd] == -1) {
							cost[nStInd] = cost[cStInd] + 1;
							states.add(nState);
							stInds.add(nStInd);
						}
					} else {
						int[] nState = Arrays.copyOf(cState, cState.length);
						nState[i]--;
						Integer nStInd = index.get(nState);
						if (nStInd == null) {
							continue;
						}
						if (cost[nStInd] == -1) {
							cost[nStInd] = cost[cStInd] + 1;
							states.add(nState);
							stInds.add(nStInd);
						}
					}
				} else if (cState[i] > cState[i + 1]) {
					int[] nState = Arrays.copyOf(cState, cState.length);
					nState[i]--;
					Integer nStInd = index.get(nState);
					if (nStInd == null) {
						continue;
					}
					if (cost[nStInd] == -1) {
						cost[nStInd] = cost[cStInd] + 1;
						states.add(nState);
						stInds.add(nStInd);
					}
				}
			}
			int[] nState = Arrays.copyOf(cState, cState.length + 1);
			nState[cState.length]++;

			Integer nStInd = index.get(nState);
			if (nStInd == null) {
				continue;
			}
			if (cost[nStInd] == -1) {
				cost[nStInd] = cost[cStInd] + 1;
				states.add(nState);
				stInds.add(nStInd);
			}
		}

		for (Entry<int[], Integer> cE : index.entrySet()) {
			int cNumD = numD[cE.getValue()];
			if (cNumD <= 300) {
				divCost[searchI][cNumD] = Math.min(divCost[searchI][cNumD], cost[cE.getValue()]);
			}
		}
	}

	static int[] cGen;

	static void genAll(int i, int max, int rem, int cProd) {
		numD[index.size()] = cProd;
		index.put(Arrays.copyOf(cGen, i), index.size());

		if (rem > 0) {
			for (int nV = Math.min(max, rem); nV >= 1; nV--) {
				cGen[i] = nV;
				genAll(i + 1, nV, rem - nV, cProd * (nV + 1));
			}
		}
	}

	static void genStart(int i, int max, int rem, int cProd) {
		start.add(Arrays.copyOf(cGen, i));

		if (i < 7) {
			for (int nV = 1; nV <= Math.min(max, rem) && cProd * (nV + 1) <= 240; nV++) {
				cGen[i] = nV;
				genStart(i + 1, nV, rem - nV, cProd * (nV + 1));
			}
		}
	}
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class Techno19_2F {

	static int MODE = -1;

	static final Comparator<int[]> COMP_ARR = new Comparator<int[]>() {
		public int compare(int[] a1, int[] a2) {
			if (MODE != -1 && (a1.length == 32 || a2.length == 32)) {
				if (a1.length == 32) {
					if (MODE < a2.length) {
						return -1;
					}
					if (MODE > a2.length) {
						return 1;
					}
				} else {
					if (a1.length < MODE) {
						return -1;
					}
					if (a1.length > MODE) {
						return 1;
					}
				}

				for (int i = 0; i < MODE; i++) {
					if (a1[i] < a2[i]) {
						return -1;
					}
					if (a1[i] > a2[i]) {
						return 1;
					}
				}
				return 0;
			} else {
				if (a1.length < a2.length) {
					return -1;
				}
				if (a1.length > a2.length) {
					return 1;
				}

				for (int i = 0; i < a2.length; i++) {
					if (a1[i] < a2[i]) {
						return -1;
					}
					if (a1[i] > a2[i]) {
						return 1;
					}
				}
				return 0;
			}
		}
	};

	static TreeMap<int[], Integer> index = new TreeMap<>(COMP_ARR);
	static int[][] states;

	static ArrayList<int[]> start = new ArrayList<>();

	static int[] numD;

	static int[] pFact = new int[1_000_001];

	static TreeMap<int[], Integer> divCostInd = new TreeMap<>(COMP_ARR);

	public static void main(String[] args) throws IOException {
		cGen = new int[23];
		numD = new int[6000];
		states = new int[6000][];
		genAll(0, 23, 23, 1);

		divCost = new int[400][301];
		for (int[] a : divCost) {
			Arrays.fill(a, Integer.MAX_VALUE / 2);
		}
		cost = new int[index.size()];

		Arrays.fill(pFact, 1);
		for (int i = 2; i <= 1_000_000; i++) {
			if (pFact[i] == 1) {
				for (int m = i; m <= 1_000_000; m += i) {
					pFact[m] = i;
				}
			}
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

		int nT = Integer.parseInt(reader.readLine());

		while (nT-- > 0) {
			StringTokenizer inputData = new StringTokenizer(reader.readLine());
			int a = Integer.parseInt(inputData.nextToken());
			int b = Integer.parseInt(inputData.nextToken());

			int[] aA = toArray(a);
			int[] bA = toArray(b);

			Integer aRes = divCostInd.get(aA);
			if (aRes == null) {
				aRes = divCostInd.size();
				bfs(aA, divCostInd.size());
				divCostInd.put(aA, divCostInd.size());
			}
			Integer bRes = divCostInd.get(bA);
			if (bRes == null) {
				bRes = divCostInd.size();
				bfs(bA, divCostInd.size());
				divCostInd.put(bA, divCostInd.size());
			}

			int minA = Integer.MAX_VALUE / 4;
			for (int nD = 1; nD <= 300; nD++) {
				minA = Math.min(minA, divCost[aRes][nD] + divCost[bRes][nD]);
			}
			printer.println(minA);
		}
		printer.close();
	}

	static int[] toArray(int a) {
		ArrayList<Integer> cnts = new ArrayList<Integer>();
		int last = -1;
		int cCnt = 0;

		while (a > 1) {
			int cPFact = pFact[a];
			if (cPFact == last) {
				cCnt++;
			} else {
				if (cCnt != 0) {
					cnts.add(cCnt);
				}
				last = cPFact;
				cCnt = 1;
			}
			a /= pFact[a];
		}
		if (cCnt != 0) {
			cnts.add(cCnt);
		}
		Collections.sort(cnts, Comparator.reverseOrder());
		int[] res = new int[cnts.size()];
		for (int i = 0; i < cnts.size(); i++) {
			res[i] = cnts.get(i);
		}
		return res;
	}

	static int[] cost;

	static int[][] divCost;

	static void bfs(int[] sState, int searchI) {
		int sInd = index.get(sState);
		ArrayDeque<Integer> stInds = new ArrayDeque<>();

		stInds.add(index.get(sState));

		Arrays.fill(cost, -1);
		cost[sInd] = 0;

		int[] cState = new int[32];

		while (!stInds.isEmpty()) {
			int cStInd = stInds.remove();
			int cLen = states[cStInd].length;
			for (int i = 0; i < cLen; i++) {
				cState[i] = states[cStInd][i];
			}
			MODE = cLen;

			for (int i = 0; i < cLen; i++) {
				if (i == 0 || cState[i - 1] > cState[i]) {
					cState[i]++;
					Integer nStInd = index.get(cState);
					cState[i]--;

					if (nStInd == null) {
						continue;
					}
					if (cost[nStInd] == -1) {
						cost[nStInd] = cost[cStInd] + 1;
						stInds.add(nStInd);
					}
				}

				if (i == cLen - 1) {
					if (cState[i] == 1) {
						MODE--;
						Integer nStInd = index.get(cState);
						MODE++;
						if (nStInd == null) {
							continue;
						}
						if (cost[nStInd] == -1) {
							cost[nStInd] = cost[cStInd] + 1;
							stInds.add(nStInd);
						}
					} else {
						cState[i]--;
						Integer nStInd = index.get(cState);
						cState[i]++;
						if (nStInd == null) {
							continue;
						}
						if (cost[nStInd] == -1) {
							cost[nStInd] = cost[cStInd] + 1;
							stInds.add(nStInd);
						}
					}
				} else if (cState[i] > cState[i + 1]) {
					cState[i]--;
					Integer nStInd = index.get(cState);
					cState[i]++;
					if (nStInd == null) {
						continue;
					}
					if (cost[nStInd] == -1) {
						cost[nStInd] = cost[cStInd] + 1;
						stInds.add(nStInd);
					}
				}
			}
			cState[cLen] = 1;

			MODE++;
			Integer nStInd = index.get(cState);
			MODE--;
			if (nStInd == null) {
				continue;
			}
			if (cost[nStInd] == -1) {
				cost[nStInd] = cost[cStInd] + 1;
				stInds.add(nStInd);
			}
		}

		for (Entry<int[], Integer> cE : index.entrySet()) {
			int cNumD = numD[cE.getValue()];
			if (cNumD <= 300) {
				divCost[searchI][cNumD] = Math.min(divCost[searchI][cNumD], cost[cE.getValue()]);
			}
		}
	}

	static int[] cGen;

	static void genAll(int i, int max, int rem, int cProd) {
		numD[index.size()] = cProd;

		int[] cKey = Arrays.copyOf(cGen, i);
		states[index.size()] = cKey;
		index.put(cKey, index.size());

		if (rem > 0) {
			for (int nV = Math.min(max, rem); nV >= 1; nV--) {
				cGen[i] = nV;
				genAll(i + 1, nV, rem - nV, cProd * (nV + 1));
			}
		}
	}
}


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

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

class TaskD {
    public static int generator (int p, int x) {
        int[] fact = new int[50];
        int cnt = 0;

        int phi = p-1,  n = phi;
        for (int i=2; i*i<=n; ++i)
            if (n % i == 0) {
                fact[cnt++]=i;
                while (n % i == 0)
                    n /= i;
            }
        if (n > 1)
            fact[cnt++]=n;

        int ret = -1;
        int temp = (x/p)*p;

        for (int res=2; res<=p; ++res) {
            boolean ok = true;
            for (int i=0; i<cnt && ok; ++i)
                ok &= MathUtils.modpow (res, phi / fact[i], p) != 1;
            if (ok) {
                int t = temp + res;
                if (t > x) t -= p;
                ret = Math.max(t, ret);
            }
        }
        return ret;
    }

    public void solve(int testNumber, Parser in, PrintWriter out) {
        int n = in.nextInt() + 1;
        int x = in.nextInt();

        if (n == 2) {
            if (x == 2) out.println(-1);
            else out.println(x-1);
            return;
        }

        if (!MathUtils.isPrime(n)) {
            out.println(-1);
            return;
        }

        int ans = generator(n, x);
        if (ans > 1 && ans < x) out.println(ans);
        else out.println(-1);
    }
}

class MathUtils {

    public static long modpow(int b, int e, int m) {
        if (e == 0) return 1%m;
        else if (e == 1) return b%m;

        long temp = modpow(b, e/2, m);
        temp = (temp * temp) % m;
        if (e % 2 == 1) temp = (temp * b) % m;

        return temp;
    }

    public static boolean isPrime(int n) {
        for (int i = 2; i*i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    }

class Parser
{
    private BufferedReader din;
    private StringTokenizer tokenizer;

    public Parser(InputStream in)
    {
        din = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

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

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

    }


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

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

class TaskD {
    public static int generator (int p, int x) {
        int[] fact = new int[50];
        int cnt = 0;

        int phi = p-1,  n = phi;
        for (int i=2; i*i<=n; ++i)
            if (n % i == 0) {
                fact[cnt++]=i;
                while (n % i == 0)
                    n /= i;
            }
        if (n > 1)
            fact[cnt++]=n;

        int ret = -1;
        int temp = (x/p)*p;

        for (int res=2; res<=p; ++res) {
            boolean ok = true;
            for (int i=0; i<cnt && ok; ++i)
                ok &= MathUtils.modpow (res, phi / fact[i], p) != 1;
            if (ok) {
                int t = temp + res;
                if (t > x) t -= p;
                ret = Math.max(t, ret);
            }
        }
        return ret;
    }

    public void solve(int testNumber, Parser in, PrintWriter out) {
        int n = in.nextInt() + 1;
        int x = in.nextInt();

        if (!MathUtils.isPrime(n)) {
            out.println(-1);
            return;
        }

        int ans = generator(n, x);
        if (ans > 1 && ans < x) out.println(ans);
        else out.println(-1);
    }
}

class MathUtils {

    public static long modpow(int b, int e, int m) {
        if (e == 0) return 1%m;
        else if (e == 1) return b%m;

        long temp = modpow(b, e/2, m);
        temp = (temp * temp) % m;
        if (e % 2 == 1) temp = (temp * b) % m;

        return temp;
    }

    public static boolean isPrime(int n) {
        for (int i = 2; i*i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    }

class Parser
{
    private BufferedReader din;
    private StringTokenizer tokenizer;

    public Parser(InputStream in)
    {
        din = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

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

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

    }


package main;

import main.Parser;
import java.io.PrintWriter;
import java.util.ArrayList;

public class TaskD {
    public static int generator (int p, int x) {
        int[] fact = new int[50];
        int cnt = 0;

        int phi = p-1,  n = phi;
        for (int i=2; i*i<=n; ++i)
            if (n % i == 0) {
                fact[cnt++]=i;
                while (n % i == 0)
                    n /= i;
            }
        if (n > 1)
            fact[cnt++]=n;

        int lim = Math.max(x-p, 1);

        for (int res=x-1; res>=lim; --res) {
            boolean ok = true;
            for (int i=0; i<cnt && ok; ++i)
                ok = MathUtils.modpow (res, phi / fact[i], p) != 1;
            if (ok) {
                return res;
            }
        }
        return -1;
    }

    public void solve(int testNumber, Parser in, PrintWriter out) {
        int n = in.nextInt() + 1;
        int x = in.nextInt();

        if (n == 2) {
            if (x == 2) out.println(-1);
            else out.println(x-1);
            return;
        }

        if (!MathUtils.isPrime(n)) {
            out.println(-1);
            return;
        }

        int ans = generator(n, x);
        if (ans > 1 && ans < x) out.println(ans);
        else out.println(-1);
    }
}


//package round183;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class B2 {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		long n = ni(), m = ni();
		long x = ni(), y = ni();
		long a = ni(), b = ni();
		long g = gcd(a, b);
		a /= g; b /= g;
		long r = Math.min(n/a, m/b);
		a *= r; b *= r;

		long min = Long.MAX_VALUE;
		long[] id = null;
		{
			long x1 = 0, y1 = 0;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		{
			long x1 = 0, y1 = m-b;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		{
			long x1 = n-a, y1 = 0;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		{
			long x1 = n-a, y1 = m-b;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		for(long y1 = y-b/2-1;y1 <= y-b/2+1;y1++){
			long x1 = 0;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		for(long y1 = y-b/2-1;y1 <= y-b/2+1;y1++){
			long x1 = n-a;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		for(long x1 = x-a/2-1;x1 <= x-a/2+1;x1++){
			long y1 = 0;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		for(long x1 = x-a/2-1;x1 <= x-a/2+1;x1++){
			long y1 = m-b;
			if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
				long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
				long[] nid = new long[]{x1, y1, x1+a, y1+b};
				if(d < min || (d == min && comp(id, nid))){
					min = d; id = nid;
				}
			}
		}
		for(long x1 = x-a/2-1;x1 <= x-a/2+1;x1++){
			for(long y1 = y-b/2-1;y1 <= y-b/2+1;y1++){
				if(x1<=x && x<=x1+a && y1<=y && y<=y1+b && x1 >= 0 && x1+a <= n && y1 >= 0 && y1+b <= m){
					long d = (long)(2*x-(2*x1+a))*(2*x-(2*x1+a))+(2*y-(2*y1+b))*(2*y-(2*y1+b));
					long[] nid = new long[]{x1, y1, x1+a, y1+b};
					if(d < min || (d == min && comp(id, nid))){
						min = d; id = nid;
					}
				}
			}
		}

		out.println(
				id[0] + " " +
				id[1] + " " +
				id[2] + " " +
				id[3]
				);
	}

	boolean comp(long[] a, long[] b){
		if(a == null)return true;
		if(b[0] < a[0])return true;
		if(b[0] > a[0])return false;
		if(b[1] < a[1])return true;
		return false;
	}

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

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new B2().run(); }

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

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

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

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

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

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

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

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

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

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

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

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            PrintWriter out = new PrintWriter(outputStream);
            G2LuckyNumbersHardVersion solver = new G2LuckyNumbersHardVersion();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class G2LuckyNumbersHardVersion {
        Debug debug = new Debug(false);

        public void solve(int testNumber, FastInput in, PrintWriter out) {
            int k = in.readInt();
            long[] f = new long[6];
            in.populate(f);
            int limit = (int) 1e6;
            long[][] dp = new long[7][limit + 1];
            long inf = (long) 1e18;
            SequenceUtils.deepFill(dp, -inf);
            dp[0][0] = 0;
            LongMinQueue queue = new LongMinQueue(limit + 1, LongComparator.REVERSE_ORDER);

            for (int i = 1, base = 1; i <= 6; i++, base *= 10) {
                long profit = f[i - 1];
                int each = base * 3;
                int threshold = (k - 1) * 3 + 1;
                for (int j = 0; j < each; j++) {
                    queue.reset();
                    for (int t = j, x = 0; t <= limit; t += each, x++) {
                        queue.addLast(dp[i - 1][t] - x * profit);
                        if (threshold < queue.size()) {
                            queue.removeFirst();
                        }
                        dp[i][t] = queue.min() + x * profit;
                    }
                }

                for (int j = limit; j >= 0; j--) {
                    for (int t = 0; t <= 9; t++) {
                        if (j - t * base < 0) {
                            continue;
                        }
                        long cand = dp[i][j - t * base];
                        if (t % 3 == 0) {
                            cand += t / 3 * profit;
                        }
                        dp[i][j] = Math.max(dp[i][j], cand);
                    }
                }
            }

            debug.debug("dp", dp);
            int q = in.readInt();
            for (int i = 0; i < q; i++) {
                int n = in.readInt();
                long ans = dp[6][n];
                out.println(ans);
            }
        }

    }

    static class Debug {
        private boolean offline;
        private PrintStream out = System.err;
        static int[] empty = new int[0];

        public Debug(boolean enable) {
            offline = enable && System.getSecurityManager() == null;
        }

        public Debug debug(String name, Object x) {
            return debug(name, x, empty);
        }

        public Debug debug(String name, Object x, int... indexes) {
            if (offline) {
                if (x == null || !x.getClass().isArray()) {
                    out.append(name);
                    for (int i : indexes) {
                        out.printf("[%d]", i);
                    }
                    out.append("=").append("" + x);
                    out.println();
                } else {
                    indexes = Arrays.copyOf(indexes, indexes.length + 1);
                    if (x instanceof byte[]) {
                        byte[] arr = (byte[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof short[]) {
                        short[] arr = (short[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof boolean[]) {
                        boolean[] arr = (boolean[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof char[]) {
                        char[] arr = (char[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof int[]) {
                        int[] arr = (int[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof float[]) {
                        float[] arr = (float[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof double[]) {
                        double[] arr = (double[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof long[]) {
                        long[] arr = (long[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else {
                        Object[] arr = (Object[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    }
                }
            }
            return this;
        }

    }

    static class LongDequeImpl implements LongDeque {
        private long[] data;
        private int bpos;
        private int epos;
        private static final long[] EMPTY = new long[0];
        private int n;

        public LongDequeImpl(int cap) {
            if (cap == 0) {
                data = EMPTY;
            } else {
                data = new long[cap];
            }
            bpos = 0;
            epos = 0;
            n = cap;
        }

        private void expandSpace(int len) {
            while (n < len) {
                n = Math.max(n + 10, n * 2);
            }
            long[] newData = new long[n];
            if (bpos <= epos) {
                if (bpos < epos) {
                    System.arraycopy(data, bpos, newData, 0, epos - bpos);
                }
            } else {
                System.arraycopy(data, bpos, newData, 0, data.length - bpos);
                System.arraycopy(data, 0, newData, data.length - bpos, epos);
            }
            epos = size();
            bpos = 0;
            data = newData;
        }

        public LongIterator iterator() {
            return new LongIterator() {
                int index = bpos;

                public boolean hasNext() {
                    return index != epos;
                }

                public long next() {
                    long ans = data[index];
                    index = LongDequeImpl.this.next(index);
                    return ans;
                }
            };
        }

        public long removeFirst() {
            long ans = data[bpos];
            bpos = next(bpos);
            return ans;
        }

        public long removeLast() {
            long ans = data[last(epos)];
            epos = last(epos);
            return ans;
        }

        public void addLast(long x) {
            ensureMore();
            data[epos] = x;
            epos = next(epos);
        }

        public long peekFirst() {
            return data[bpos];
        }

        public long peekLast() {
            return data[last(epos)];
        }

        public void clear() {
            bpos = epos = 0;
        }

        private int last(int x) {
            return (x == 0 ? n : x) - 1;
        }

        private int next(int x) {
            return x + 1 >= n ? 0 : x + 1;
        }

        private void ensureMore() {
            if (next(epos) == bpos) {
                expandSpace(n + 1);
            }
        }

        public int size() {
            int ans = epos - bpos;
            if (ans < 0) {
                ans += data.length;
            }
            return ans;
        }

        public boolean isEmpty() {
            return bpos == epos;
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            for (LongIterator iterator = iterator(); iterator.hasNext(); ) {
                builder.append(iterator.next()).append(' ');
            }
            return builder.toString();
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

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

        public void populate(long[] data) {
            for (int i = 0; i < data.length; i++) {
                data[i] = readLong();
            }
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public long readLong() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            long val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class LongMinQueue {
        LongDequeImpl minQueue;
        LongDequeImpl data;
        LongComparator comparator;

        public LongMinQueue(int cap, LongComparator comparator) {
            minQueue = new LongDequeImpl(cap);
            data = new LongDequeImpl(cap);
            this.comparator = comparator;
        }

        public void reset() {
            minQueue.clear();
            data.clear();
        }

        public void addLast(long val) {
            data.addLast(val);
            while (!minQueue.isEmpty() && comparator.compare(minQueue.peekLast(), val) > 0) {
                minQueue.removeLast();
            }
            minQueue.addLast(val);
        }

        public long removeFirst() {
            long val = data.removeFirst();
            if (minQueue.peekFirst() == val) {
                minQueue.removeFirst();
            }
            return val;
        }

        public int size() {
            return data.size();
        }

        public long min() {
            return minQueue.peekFirst();
        }

    }

    static interface LongDeque extends LongStack {
    }

    static interface LongComparator {
        public static final LongComparator REVERSE_ORDER = (a, b) -> Long.compare(b, a);

        public int compare(long a, long b);

    }

    static class SequenceUtils {
        public static void deepFill(Object array, long val) {
            if (!array.getClass().isArray()) {
                throw new IllegalArgumentException();
            }
            if (array instanceof long[]) {
                long[] longArray = (long[]) array;
                Arrays.fill(longArray, val);
            } else {
                Object[] objArray = (Object[]) array;
                for (Object obj : objArray) {
                    deepFill(obj, val);
                }
            }
        }

    }

    static interface LongStack {
    }

    static interface LongIterator {
        boolean hasNext();

        long next();

    }
}


//package raif;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class G3 {
	InputStream is;
	PrintWriter out;
//	String INPUT = "999999 1 2 3 4 5 6 1 999999";
	String INPUT = "";

	void solve()
	{
		int K = ni();
		long[] F = nal(6);
		long I = Long.MIN_VALUE / 2;
		for(int Q = ni();Q > 0;Q--){
			int n = ni();
			long[] dp = {0L};
			for(int i = 0;i < 6;i++, n /= 10){
				int dd = n % 10;
				long[] ndp = new long[n/10+1];
				Arrays.fill(ndp, I);
				SegmentTreeRMQL[] st = new SegmentTreeRMQL[3];
				for(int j = 0;j < 3;j++){
					long[] b = new long[dp.length/3+1];
					for(int k = j;k < dp.length;k+=3){
						b[k/3] = -(dp[k] - F[i] * (k/3));
					}
					st[j] = new SegmentTreeRMQL(b);
				}

				for(int c = 0;c < ndp.length;c++){
					int val = c*10 + dd;
					// val-t <= 9k
					for(int rem = 0;rem < 3;rem++) {
						int inf = Math.max(val-9*(K-1), 0);
						int sup = Math.min(dp.length-1, val);
						inf = Math.max(0, (inf+3-rem)/3-1);
						sup = (sup+3-rem)/3-1;
//						tr(inf, sup+1, dp.length/3+1);
						long v = -st[rem].min(inf, sup+1) + (val-rem)/3*F[i];
						ndp[c] = Math.max(ndp[c], v);
					}
					for(int t = Math.max(val-9*K, 0);t <= val-9*(K-1) && t < dp.length;t++){
						int m = val-t;
						int got = m/3;
						if(m % 3 != 0){
							got = 3*(K-1);
						}
						ndp[c] = Math.max(ndp[c], got*F[i] + dp[t]);
					}
				}
				dp = ndp;
			}
			out.println(dp[0]);
		}
	}

	public static class SegmentTreeRMQL {
		public final int M, H, N;
		public long[] vals;
		public static final long I = Long.MAX_VALUE/3;

		public SegmentTreeRMQL(int n)
		{
			N = n;
			M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
			H = M>>>1;
			vals = new long[M];
			Arrays.fill(vals, 0, M, I);
		}

		public SegmentTreeRMQL(long[] a)
		{
			this(a.length);
			for(int i = 0;i < N;i++){
				vals[H+i] = a[i];
			}
			//		Arrays.fill(vals, H+N, M, I);
			for(int i = H-1;i >= 1;i--)propagate(i);
		}

		public void update(int pos, long x)
		{
			vals[H+pos] = x;
			for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i);
		}

		private void propagate(int i)
		{
			vals[i] = Math.min(vals[2*i], vals[2*i+1]);
		}

		public long min(int l, int r){
			long min = I;
			if(l >= r)return min;
			l += H; r += H;
			for(;l < r;l>>>=1,r>>>=1){
				if((l&1) == 1)min = Math.min(min, vals[l++]);
				if((r&1) == 1)min = Math.min(min, vals[--r]);
			}
			return min;
		}

		public int firstle(int l, long v) {
			if(l >= H)return -1;
			int cur = H+l;
			while(true){
				if(vals[cur] <= v){
					if(cur >= H)return cur-H;
					cur = 2*cur;
				}else{
					cur++;
					if((cur&cur-1) == 0)return -1;
					if((cur&1)==0)cur>>>=1;
				}
			}
		}

		public int lastle(int l, long v) {
			if(l < 0)return -1;
			int cur = H+l;
			while(true){
				if(vals[cur] <= v){
					if(cur >= H)return cur-H;
					cur = 2*cur + 1;
				}else{
					if((cur&cur-1) == 0)return -1;
					cur--;
					if((cur&1)==1)cur>>>=1;
				}
			}
		}
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new G3().run(); }

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

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

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

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

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

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

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

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

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

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

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

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

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;

public class Main {

	public static void main(String[] args) throws IOException {
		try {
			if (new File("input.txt").exists())
				System.setIn(new FileInputStream("input.txt"));
		} catch (SecurityException e) {
		}
		new Thread(null, new Runnable() {
			public void run() {
				try {
					new Main().run();
				} catch (Throwable e) {
					e.printStackTrace();
					exit(999);
				}
			}
		}, "1", 1 << 23).start();
	}

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	private void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		in.close();
		out.close();
	}

	final int m = 5;
	final double ANGLE = toRadians(36);
	private int[][] num;
	private int sNum;

	private void solve() throws IOException {
		Point[] nextVect = new Point[m];
		{
			Point prev = new Point(10, 0);
			for (int i = 0, k = 0; k < m; i = (i + 2) % 5, k++)
				prev = nextVect[i] = prev.rotate(i == 0 ? ANGLE : (PI - ANGLE));
//			System.err.println(Arrays.toString(nextVect));
//			System.err.println(nextVect[4].dist());
		}

		sNum = nextInt();

		Point[][] pnt = new Point[sNum][m];
		num = new int[sNum][m];
		int cnt = 1;
		ArrayList<Point> pn = new ArrayList<Main.Point>();
		for (int i = 0; i < sNum; i++) {
			if (i == 0) {
				pnt[i][0] = new Point(0, 0);
				num[i][0] = 1;
				pn.add(pnt[i][0]);
			} else {
				pnt[i][0] = pnt[i - 1][2];
				num[i][0] = num[i - 1][2];
			}
			for (int j = 0; j < m - 1; j++) {
				pnt[i][j + 1] = pnt[i][j].add(nextVect[j]);
				num[i][j + 1] = ++cnt;
				pn.add(pnt[i][j + 1]);
			}
		}
		out.println(pn.size());
		for (Point p : pn)
			out.println(p);
		for (int i = 0; i < sNum; i++) {
			for (int j = 0; j < m; j++) {
				if (j != 0)
					out.print(' ');
				out.print(num[i][j]);
			}
			out.println();
		}
		out.print(1);
		print(0);
		out.println();
	}

	void print(int s) {
		if (s == sNum)
			return;
		out.print(' ');
		out.print(num[s][2]);
		print(s + 1);
		for (int i = 4; i != 2; i = (i + 2) % 5) {
			out.print(' ');
			out.print(num[s][i]);
		}
	}

	double getLen() {
		double a = 10;
		double b = 10;
		double phi = toRadians(108);
		return sqrt(a * a + b * b - 2 * a * b * cos(phi));
	}

	class Point {
		double x, y;

		public Point(double x, double y) {
			this.x = x;
			this.y = y;
		}

		public Point rotate(double phi) {
			double cos = cos(phi);
			double sin = sin(phi);
			return new Point(x * cos - y * sin, x * sin + y * cos);
		}

		public Point add(Point v) {
			return new Point(x + v.x, y + v.y);
		}

		@Override
		public String toString() {
			return String.format("%.9f %.9f", x, y);
		}
		double dist() {
			return sqrt(x * x + y * y);
		}
	}

	void chk(boolean b) {
		if (b)
			return;
		System.out.println(new Error().getStackTrace()[1]);
		exit(999);
	}
	void deb(String fmt, Object... args) {
		System.out.printf(Locale.US, fmt + "%n", args);
	}
	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}
	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}
	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}
}


import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.*;
import java.math.*;

import static java.lang.Math.*;

public class Solution implements Runnable {

    void solve() throws Exception {
    	int n = sc.nextInt();
    	int m = 5 + (n - 1) * 4;
    	double[] x = new double[m];
    	double[] y = new double[m];
    	double ang72 = 72.0 * PI / 180.0;
    	double ang18 = 18.0 * PI / 180.0;
    	double ang36 = 36.0 * PI / 180.0;
    	x[0] = -4000;
    	y[0] = -4000;
    	x[1] = x[0] + 10;
    	y[1] = y[0];
    	x[2] = x[1] + 10.0 * cos(ang72);
    	y[2] = y[1] + 10.0 * sin(ang72);
    	x[3] = x[2] - 10.0 * cos(ang36);
    	y[3] = y[2] + 10.0 * sin(ang36);
    	x[4] = x[0] - 10.0 * sin(ang18);
    	y[4] = y[0] + 10.0 * cos(ang18);
    	for (int i = 5; i < m; i++) {
    		x[i] = x[i - 4] + (x[3] - x[0]);
    		y[i] = y[i - 4] + (y[3] - y[0]);
    	}
    	out.println(m);
    	for (int i = 0; i < m; i++) {
    		out.format("%.12f %.12f%n", x[i], y[i]);
    	}
    	for (int i = 0; i < n; i++) {
    		if (i == 0) {
    			for (int j = 0; j < 5; j++) {
    				out.print((j + 1) + " ");
    			}
    		} else {
    			out.print((3 + 4 * (i - 1) + 1) + " ");
    			for (int j = 0; j < 4; j++) {
    				out.print((5 + 4 * (i - 1) + j + 1) + " ");
    			}
    		}
    		out.println();
    	}
    	out.print("1 4 ");
    	int lst = 3;
    	for (int i = 7; i < m; i += 4) {
    		out.print((i + 1) + " ");
    		lst = i;
    	}
    	for (int i = n - 1; i > 0; --i) {
    		out.print((lst - 2 + 1) + " ");
    		out.print((lst + 1 + 1) + " ");
    		out.print((lst - 1 + 1) + " ");
    		out.print((lst - 4 + 1) + " ");
    		lst -= 4;
    	}
    	out.println("2 5 3 1");
    }

    BufferedReader in;
    PrintWriter out;
    FastScanner sc;

    final String INPUT_FILE = "stdin";
    final String OUTPUT_FILE = "stdout";

    static Throwable throwable;

    public static void main(String[] args) throws Throwable {
        Thread thread = new Thread(null, new Solution(), "", (1 << 26));
        thread.start();
        thread.join();
        thread.run();
        if (throwable != null)
            throw throwable;
    }

    public void run() {
        try {
            if (INPUT_FILE.equals("stdin"))
                in = new BufferedReader(new InputStreamReader(System.in));
            else
                in = new BufferedReader(new FileReader(INPUT_FILE));
            if (OUTPUT_FILE.equals("stdout"))
                out = new PrintWriter(System.out);
            else
                out = new PrintWriter(new FileWriter(OUTPUT_FILE));
            sc = new FastScanner(in);
            solve();
        } catch (Exception e) {
            throwable = e;
        } finally {
            out.close();
        }
    }
}

class FastScanner {
    BufferedReader reader;
    StringTokenizer strTok;

    FastScanner(BufferedReader reader) {
        this.reader = reader;
    }

    public String nextToken() throws Exception {
        while (strTok == null || !strTok.hasMoreTokens())
            strTok = new StringTokenizer(reader.readLine());
        return strTok.nextToken();
    }

    public boolean EOF() throws Exception {
    	if (strTok != null && strTok.hasMoreTokens()) {
    		return false;
    	} else {
    		String line = reader.readLine();
    		if (line == null)
    			return true;
    		strTok = new StringTokenizer(line);
    		return false;
    	}
    }

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

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

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


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

public class d
{
    static int N;
    static String d1 = "13.090169943749474241"; // 10 + 10sin18
    static String d2 = "9.5105651629515357212"; // 10cos18
    static String d3 = "16.180339887498948482"; // 10 + 20sin18
    static String d4 = "15.388417685876267013"; // 5 tan 72
    static double d, e, f, g;

    static ArrayList<Pair> points = new ArrayList<Pair>();
    static ArrayList<Integer> pq1 = new ArrayList<Integer>();
    static ArrayList<Integer> pq2 = new ArrayList<Integer>();

    static int go(double x, double y)
    {
        Pair next = new Pair(x, y);
        for (int i = 0; i < points.size(); i++)
            if (points.get(i).equals(next))
                return i;
        points.add(next);
        System.out.printf("%.15f %.15f\n", next.x, next.y);
        return points.size() - 1;
    }

    static void solve(double x, double y, int n)
    {
        if (n >= N)
            return;

        if (n % 2 == 0) // right-side up
        {
            int[] idx = new int[6];
            idx[0] = go(x, y);

            double next_x = x + d;
            double next_y = y - e;
            double cx = next_x;
            double cy = next_y;
            idx[1] = go(next_x, next_y);
            pq2.add(idx[1]);
            solve(cx, cy, n + 1);

            next_x -= 5.0;
            next_y += g;
            idx[2] = go(next_x, next_y);
            pq2.add(idx[2]);

            next_x -= 5.0;
            next_y -= g;
            idx[3] = go(next_x, next_y);
            pq2.add(idx[3]);

            next_x += d;
            next_y += e;
            idx[4] = go(next_x, next_y);
            pq2.add(idx[4]);

            next_x -= f;
            idx[5] = go(next_x, next_y);
            pq2.add(idx[5]);

            pq1.add(idx[0]);
            pq1.add(idx[3]);
            pq1.add(idx[1]);
            pq1.add(idx[4]);
            pq1.add(idx[2]);
        }
        else // upside-down
        {
            int[] idx = new int[6];
            idx[0] = go(x, y);

            double next_x = x + d;
            double next_y = y + e;
            double cx = next_x;
            double cy = next_y;
            idx[1] = go(next_x, next_y);
            pq2.add(idx[1]);
            solve(cx, cy, n + 1);

            next_x -= 5.0;
            next_y -= g;
            idx[2] = go(next_x, next_y);
            pq2.add(idx[2]);

            next_x -= 5.0;
            next_y += g;
            idx[3] = go(next_x, next_y);
            pq2.add(idx[3]);

            next_x += d;
            next_y -= e;
            idx[4] = go(next_x, next_y);
            pq2.add(idx[4]);

            next_x -= f;
            idx[5] = go(next_x, next_y);
            pq2.add(idx[5]);

            pq1.add(idx[0]);
            pq1.add(idx[3]);
            pq1.add(idx[1]);
            pq1.add(idx[4]);
            pq1.add(idx[2]);
        }
    }

    public static void main(String[] args) throws IOException
    {
        d = Double.parseDouble(d1);
        e = Double.parseDouble(d2);
        f = Double.parseDouble(d3);
        g = Double.parseDouble(d4);

        BufferedReader w = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(w.readLine());

        points.add(new Pair(-1.0e10, -1.0e10));

        System.out.println(2 + N * 3);
        solve(0.0, 0.0, 0);
        for (int i = 0; i < pq1.size(); i += 5)
            for (int j = i; j < i + 5; j++)
            {
                System.out.print(pq1.get(j));
                if (j == i + 4) System.out.print("\n");
                else System.out.print(" ");
            }
        System.out.print("1");
        for (int i = 0; i < pq2.size(); i++)
            System.out.print(" " + pq2.get(i));
        System.out.println();

        System.exit(0);
    }

    public static class Pair
    {
        double x, y;
        double epsilon = 1.0e-7;
        public Pair(double a, double b)
        {
            x = a;
            y = b;
        }

        public boolean equals(Pair other)
        {
            return Math.abs(other.x - x) + Math.abs(other.y - y) < epsilon;
        }
    }
}


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

public class d
{
    static int N;
    static String d1 = "13.090169943749474241"; // 10 + 10sin18
    static String d2 = "9.5105651629515357212"; // 10cos18
    static String d3 = "16.180339887498948482"; // 10 + 20sin18
    static String d4 = "15.388417685876267013"; // 5 tan 72
    static double d, e, f, g;

    static ArrayList<Pair> points = new ArrayList<Pair>();;

    static int go(double x, double y)
    {
        Pair next = new Pair(x, y);
        for (int i = 0; i < points.size(); i++)
            if (points.get(i).equals(next))
                return i;
        points.add(next);
        System.out.printf("%.15f %.15f\n", next.x, next.y);
        return points.size() - 1;
    }

    static void solve(double x, double y, int n, boolean print_out)
    {
        if (n >= N)
            return;

        if (n % 2 == 0) // right-side up
        {
            int[] idx = new int[6];
            idx[0] = go(x, y);

            double next_x = x + d;
            double next_y = y - e;
            double cx = next_x;
            double cy = next_y;
            idx[1] = go(next_x, next_y);

            next_x -= 5.0;
            next_y += g;
            idx[2] = go(next_x, next_y);

            next_x -= 5.0;
            next_y -= g;
            idx[3] = go(next_x, next_y);

            next_x += d;
            next_y += e;
            idx[4] = go(next_x, next_y);

            next_x -= f;
            idx[5] = go(next_x, next_y);

            if (print_out)
            {
                System.out.printf("%d %d %d %d %d\n", idx[0], idx[3], idx[1], idx[4], idx[2]);
                System.out.printf("%d %d %d %d %d %d\n", idx[0], idx[1], idx[2], idx[3], idx[4], idx[5]);
            }

            solve(cx, cy, n + 1, print_out);
        }
        else // upside-down
        {
            int[] idx = new int[6];
            idx[0] = go(x, y);

            double next_x = x + d;
            double next_y = y + e;
            double cx = next_x;
            double cy = next_y;
            idx[1] = go(next_x, next_y);

            next_x -= 5.0;
            next_y -= g;
            idx[2] = go(next_x, next_y);

            next_x -= 5.0;
            next_y += g;
            idx[3] = go(next_x, next_y);

            next_x += d;
            next_y -= e;
            idx[4] = go(next_x, next_y);

            next_x -= f;
            idx[5] = go(next_x, next_y);

            if (print_out)
            {
                System.out.printf("%d %d %d %d %d\n", idx[0], idx[3], idx[1], idx[4], idx[2]);
                System.out.printf("%d %d %d %d %d %d\n", idx[0], idx[1], idx[2], idx[3], idx[4], idx[5])
            }

            solve(cx, cy, n + 1, print_out);
        }
    }

    public static void main(String[] args) throws IOException
    {
        d = Double.parseDouble(d1);
        e = Double.parseDouble(d2);
        f = Double.parseDouble(d3);
        g = Double.parseDouble(d4);

        BufferedReader w = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(w.readLine());

        points.add(new Pair(-1.0e10, -1.0e10));

        System.out.println(2 + N * 3);
        solve(0.0, 0.0, 0, false);
        solve(0.0, 0.0, 0, true);

        System.exit(0);
    }

    public static class Pair
    {
        double x, y;
        double epsilon = 1.0e-7;
        public Pair(double a, double b)
        {
            x = a;
            y = b;
        }

        public boolean equals(Pair other)
        {
            return Math.abs(other.x - x) + Math.abs(other.y - y) < epsilon;
        }
    }
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.Queue;

/*
	br = new BufferedReader(new FileReader("input.txt"));
	pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
	br = new BufferedReader(new InputStreamReader(System.in));
	pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static Set<State> seen, win;

	static BigInteger n;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int qq = 1;
		//int qq = Integer.MAX_VALUE;
		//int qq = readInt();
		for(int casenum = 1; casenum <= qq; casenum++)	{
			int a = readInt();
			int b = readInt();
			n = new BigInteger(nextToken());
			if(a == 1 && BigInteger.valueOf(a+1).pow(b).compareTo(n) >= 0)	{
				pw.println("Missing");
			}
			else	{
				seen = new HashSet<Main.State>();
				win = new HashSet<Main.State>();
				pw.println(win(a,b) ? "Masha" : "Stas");
			}
		}
		pw.close();
	}

	private static boolean win(int a, int b) {
		if(seen.add(new State(a,b)))	{
			if(BigInteger.valueOf(a).pow(b).compareTo(n) >= 0)		{
				return true;
			}
			else if(b == 1 && BigInteger.valueOf(a+1).pow(b).compareTo(n) >= 0)	{
				if(a%2 == n.intValue()%2)	{
					win.add(new State(a,b));
					return true;
				}
				else	{
					return false;
				}
			}
			if(!win(a+1,b) || !win(a,b+1))	{
				win.add(new State(a,b));
				return true;
			}
			return false;
		}
		return win.contains(new State(a,b));
	}

	static class State	{
		public int x,y;

		public State(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + x;
			result = prime * result + y;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			State other = (State) obj;
			if (x != other.x)
				return false;
			if (y != other.y)
				return false;
			return true;
		}

	}

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

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


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

public class Main {
    static int MOD = 1000000007;

    // After writing solution, quick scan for:
    //   array out of bounds
    //   special cases e.g. n=1?
    //
    // Big numbers arithmetic bugs:
    //   int overflow
    //   sorting, or taking max, after MOD
    void solve() throws IOException {
        int[] abn = ril(3);
        int a = abn[0];
        int b = abn[1];
        int n = abn[2];
        if (a == 1 && Math.pow(a+1, b) >= n) {
            pw.println("Missing");
            return;
        }
        pw.println(dfs(a, b, n) ? "Masha" : "Stas");
    }

    Map<Integer, Map<Integer, Boolean>> memo = new HashMap<>();
    boolean dfs(int a, int b, int n) {
        if (Math.pow(a, b) >= n) return true;
        if (memo.containsKey(a) && memo.get(a).containsKey(b)) return memo.get(a).get(b);
        if (!memo.containsKey(a)) memo.put(a, new HashMap<>());
        boolean move1 = dfs(a+1, b, n);
        if (!move1) {
            memo.get(a).put(b, Boolean.TRUE);
            return true;
        }
        boolean move2 = dfs(a, b+1, n);
        if (!move2) {
            memo.get(a).put(b, Boolean.TRUE);
            return true;
        }
        memo.get(a).put(b, Boolean.FALSE);
        return false;
    }

    // Template code below

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {
        Main m = new Main();
        m.solve();
        m.close();
    }

    void close() throws IOException {
        pw.flush();
        pw.close();
        br.close();
    }

    int ri() throws IOException {
        return Integer.parseInt(br.readLine().trim());
    }

    long rl() throws IOException {
        return Long.parseLong(br.readLine().trim());
    }

    int[] ril(int n) throws IOException {
        int[] nums = new int[n];
        int c = 0;
        for (int i = 0; i < n; i++) {
            int sign = 1;
            c = br.read();
            int x = 0;
            if (c == '-') {
                sign = -1;
                c = br.read();
            }
            while (c >= '0' && c <= '9') {
                x = x * 10 + c - '0';
                c = br.read();
            }
            nums[i] = x * sign;
        }
        while (c != '\n' && c != -1) c = br.read();
        return nums;
    }

    long[] rll(int n) throws IOException {
        long[] nums = new long[n];
        int c = 0;
        for (int i = 0; i < n; i++) {
            int sign = 1;
            c = br.read();
            long x = 0;
            if (c == '-') {
                sign = -1;
                c = br.read();
            }
            while (c >= '0' && c <= '9') {
                x = x * 10 + c - '0';
                c = br.read();
            }
            nums[i] = x * sign;
        }
        while (c != '\n' && c != -1) c = br.read();
        return nums;
    }

    int[] rkil() throws IOException {
        int sign = 1;
        int c = br.read();
        int x = 0;
        if (c == '-') {
            sign = -1;
            c = br.read();
        }
        while (c >= '0' && c <= '9') {
            x = x * 10 + c - '0';
            c = br.read();
        }
        return ril(x);
    }

    long[] rkll() throws IOException {
        int sign = 1;
        int c = br.read();
        int x = 0;
        if (c == '-') {
            sign = -1;
            c = br.read();
        }
        while (c >= '0' && c <= '9') {
            x = x * 10 + c - '0';
            c = br.read();
        }
        return rll(x);
    }

    char[] rs() throws IOException {
        return br.readLine().toCharArray();
    }

    void sort(int[] A) {
        Random r = new Random();
        for (int i = A.length-1; i > 0; i--) {
            int j = r.nextInt(i+1);
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
        Arrays.sort(A);
    }
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.Queue;

/*
	br = new BufferedReader(new FileReader("input.txt"));
	pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
	br = new BufferedReader(new InputStreamReader(System.in));
	pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static Set<State> seen, win;

	static BigInteger n;

	static boolean draw;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int qq = 1;
		//int qq = Integer.MAX_VALUE;
		//int qq = readInt();
		for(int casenum = 1; casenum <= qq; casenum++)	{
			int a = readInt();
			draw = false;
			int b = readInt();
			n = new BigInteger(nextToken());
			if(a == 1 && BigInteger.valueOf(a+1).pow(b).compareTo(n) >= 0)	{
				pw.println("Missing");
			}
			else	{
				seen = new HashSet<Main.State>();
				win = new HashSet<Main.State>();
				boolean ret = win(a,b,0);
				if(draw && !ret)	{
					pw.println("Missing");
				}
				else	{
					pw.println(ret ? "Masha" : "Stas");
				}
			}
		}
		pw.close();
	}

	private static boolean win(int a, int b, int d) {
		if(seen.add(new State(a,b)))	{
			if(BigInteger.valueOf(a).pow(b).compareTo(n) >= 0)		{
				return true;
			}
			else if(b == 1 && BigInteger.valueOf(a+1).pow(b).compareTo(n) >= 0)	{
				if(a%2 == n.intValue()%2)	{
					win.add(new State(a,b));
					return true;
				}
				else	{
					return false;
				}
			}
			else if(a == 1 && BigInteger.valueOf(a+1).pow(b).compareTo(n) >= 0)	{
				if(d%2 == 0)	{
					draw = true;
					return false;
				}
				win.add(new State(a,b));
				return true;
			}
			else if(!win(a,b+1,d+1) || !win(a+1,b,d+1))	{
				win.add(new State(a,b));
				return true;
			}
			return false;
		}
		return win.contains(new State(a,b));
	}

	static class State	{
		public int x,y;

		public State(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + x;
			result = prime * result + y;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			State other = (State) obj;
			if (x != other.x)
				return false;
			if (y != other.y)
				return false;
			return true;
		}

	}

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

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


//package school1;

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

public class E {

	static StreamTokenizer in =
		new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

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

	static PrintWriter out = new PrintWriter(System.out);

	public static void main(String[] args) throws IOException{
		int a = nextInt(),
			b = nextInt(),
			n = nextInt();

		if (a==1 && Math.pow(2, b)>=n){
			out.println("Missing");
			out.flush();
			return;
		}

		int B[] = new int[100];
		B[1] = n-1;
		int p = (int)Math.sqrt(n);
		B[2] = p;
		for (int i=3; i<=30; i++)
			for (int j=p; j>=2; j--)
				if (Math.pow(j, i) < n){
					B[i] = j;
					p = j;
					break;
				}

		for (int i=b; i<=30; i++)
			if (B[i] >= a){
				if (i-b == B[i]-a){
					out.println("Stas");
					out.flush();
					return;
				}
				else if (Math.abs((i-b)-(B[i]-a)) == 1){
					out.println("Masha");
					out.flush();
					return;
				}
			}
	}

}


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

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);
		Set<Integer> S= new HashSet<> ();
		Set<Integer> Q= new HashSet<> ();
		S.add(0) ;
		long [] d= new long[105];
		for (int i=1; i<=10; i++) {
			for (int j:S) {
				Q.add(j+1);
				Q.add(j+5);
				Q.add(j+10);
				Q.add(j+50);
			}
			S= new HashSet<Integer> (Q);
			Q.clear();
			d[i]=S.size();
		}
		long n=in.nextLong();
		if (n<=100) out.println(d[(int) n]);
		else{
			out.println(d[100]+(n-100)*49);
		}

        out.close();
    }

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

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

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

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

    }
}


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

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

    static class BRomanDigits {
        long easySolve(int i) {
            int[] dp = new int[]{0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292, 341, 390, 439, 488, 537, 586, 635, 684, 733, 782, 831, 880, 929, 978, 1027, 1076, 1125, 1174};
            if (i < dp.length) {
                return dp[i];
            } else {
                long[] y = new long[]{782, 831, 880, 929};
                long[] x = new long[]{21, 22, 23, 24};
                return LagrangeInterpolation.interpolate(x, y, i);
            }
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int i = in.NextInt();
            out.println(easySolve(i));
        }

    }

    static class LagrangeInterpolation {
        public static long interpolate(long[] x, long[] y, long xi) {
            double result = 0;
            final int n = x.length;
            for (int i = 0; i < n; i++) {
                double term = y[i];
                for (int j = 0; j < n; j++) {
                    if (j != i)
                        term = term * (double) (xi - x[j]) / (double) (x[i] - x[j]);
                }
                result += term;
            }
            return Math.round(result);
        }

    }

    static class InputReader {
        BufferedReader reader;
        StringTokenizer tokenizer;

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

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

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

    }
}


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

public class B {
	public static void main(String[] args) throws IOException {

		/**/
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
		/*/
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
		/**/

		int n = sc.nextInt();
		int[] len = new int[85];
		len[9] = 1;
		len[18] = 2;
		len[27] = 3;
		len[36] = 4;
		len[45] = 5;
		len[54] = 6;
		len[63] = 7;
		len[72] = 8;
		len[4] = 1;
		for (int i = 4; i < 85; i++) {
			if (len[i-4] != 0) {
				if (len[i]==0||len[i-4]+1<len[i])
					len[i]=len[i-4]+1;
			}
		}
		len[49]=0;
		for (int i = 50; i < 85; i++) {
			if (len[i-49]>0)
				len[i] = 0;
		}
		int ans = 0;
		for (int i = 0; i < 85; i++) {
			if (i>0&&len[i]==0)
				continue;
			int num = n-len[i];
			if (num>=0)
				ans += num+1;
		}
		System.out.println(ans);
	}
}


//package codeforces;

/**
 * Created by sky on 2/7/18.
 * www.github.com/aakashjaiswal1
 * aakashjaiswal@hotmail.co.in
 * aakashjaiswal.in@gmail.com
 * people die if they are killed
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by sky on 13/4/18.
 * www.github.com/aakashjaiswal1
 * aakashjaiswal@hotmail.co.in
 * aakashjaiswal.in@gmail.com
 * people die if they are killed
 */
  public class defaul {
    public static void main(String[] args) {
        in = new FastReader();
        int no=ni();
        int[] arr={0,4,10,20,35,56,83,116,155,198,244,292,341,390};
        if (no<arr.length) {System.out.println(arr[no]);return;}
        int base=13;
        int extra=no-base;
        long ans=390L+49*extra;
        System.out.println(ans);

    }
    public static long binarySearch(long low, long high) {
        while (high - low > 1) {
            long mid = (high - low)/2 + low;
            //System.out.println(mid);
            if (works(mid)) {
                high = mid;
            } else {
                low = mid;
            }
        }
        return (works(low) ? low : high);
    }
    static private boolean works(long test){
        return true;
    }

    static void reverse(char[] arr ,int i,int j){
        if (i==j)
            return;
        while (i<j){
            char temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
            ++i;
            --j;
        }
    }
    static int[]  takeIntegerArrayInput(int no){
        int[] arr=new int[no];
        for (int i=0;i<no;++i){
            arr[i]=ni();
        }
        return arr;
    }
    static long fast_Multiply(long no , long pow){
        long result=1;
        while (pow>0){
            if ((pow&1)==1){
                result=result*no;
            }
            no=no*no;
            pow>>=1;
        }
        return result;
    }

    static long[]  takeLongArrayInput(int no){
        long[] arr=new long[no];
        for (int i=0;i<no;++i){
            arr[i]=ni();
        }
        return arr;
    }
    static final long MOD = (long)1e9+7;
    static FastReader in;

    static void p(Object o){
        System.out.print(o);
    }

    static void pn(Object o){
        System.out.println(o);
    }

    static String n(){
        return in.next();
    }

    static String nln(){
        return in.nextLine();
    }

    static int ni(){
        return Integer.parseInt(in.next());
    }

    static int[] ia(int N){
        int[] a = new int[N];
        for(int i = 0; i<N; i++)a[i] = ni();
        return a;
    }

    static long[] la(int N){
        long[] a = new long[N];
        for(int i = 0; i<N; i++)a[i] = nl();
        return a;
    }

    static long nl(){
        return Long.parseLong(in.next());
    }

    static double nd(){
        return Double.parseDouble(in.next());
    }

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

        String nextLine(){
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                e.printStackTrace();
            }
            return str;
        }
    }
    static void println(String[] arr){
        for (int i=0;i<arr.length;++i){
            System.out.println(arr[i]);
        }
    }

}


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

public class D {

	static StringTokenizer st;
	static BufferedReader br;
	static PrintWriter pw;
	static double[]sin, cos;
	static double s, d, cosalfa, sinalfa, q, r;
	static int xx, yy, ii;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = nextInt();
		int L = nextInt();
		int R = nextInt();
		double[][]dp = new double[n][1 << n];
		for (int i = 0; i < n; i++) {
			Arrays.fill(dp[i], L);
		}
		int[]x = new int[n], y = new int[n];
		double[]a = new double[n];
		sin = new double[n];
		cos = new double[n];
		for (int i = 0; i < n; i++) {
			x[i] = nextInt();
			y[i] = nextInt();
			a[i] = nextDouble();
			sin[i] = Math.sin(Math.toRadians(a[i]));
			cos[i] = Math.cos(Math.toRadians(a[i]));
		}
		for (int i = 0; i < n; i++) {
			s = L;
			xx = x[i];
			yy = y[i];
			ii = i;
			dp[i][1 << i] = calc();
		}
		for (int mask = 0; mask < (1 << n); mask++) {
			for (int i = 0; i < n; i++) {
				if ((mask & (1 << i)) != 0) {
					for (int j = 0; j < n; j++) {
						if ((mask & (1 << j))==0) {
							s = dp[i][mask];
							xx = x[j];
							yy = y[j];
							ii = j;
							dp[j][mask | (1 << j)] = Math.max(dp[j][mask | (1 << j)], calc());
						}
					}
				}
			}
		}
		double max = L;
		for (int mask = 0; mask < (1 << n); mask++) {
			for (int i = 0; i < n; i++) {
				max = Math.max(max, dp[i][mask]);
			}
		}
		if (max > R)
			max = R;
		pw.println(max-L);
		pw.close();
	}
	private static double calc() {
		d = Math.sqrt((xx-s)*(xx-s)+yy*yy);
		sinalfa = yy / d;
		cosalfa = (xx-s) / d;
		q = sin[ii]*cosalfa+cos[ii]*sinalfa;
		if (q < 0)
			return 1e9;
		r = d * sin[ii] / q;
		return s+r;
	}
	private static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}
	private static long nextLong() throws IOException {
		return Long.parseLong(next());
	}
	private static double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}
	private static String next() throws IOException {
		while (st==null || !st.hasMoreTokens())
			st = new StringTokenizer(br.readLine());
		return st.nextToken();
	}
}
/*
20 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
*/


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

public class D {

    static StringTokenizer st;
    static BufferedReader br;
    static PrintWriter pw;
    static double[]sin, cos;
    static double s;
    static int xx, yy, ii;
    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int L = nextInt();
        int R = nextInt();
        double[][]dp = new double[n][1 << n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(dp[i], L);
        }
        int[]x = new int[n], y = new int[n];
        double[]a = new double[n];
        sin = new double[n];
        cos = new double[n];
        for (int i = 0; i < n; i++) {
            x[i] = nextInt();
            y[i] = nextInt();
            a[i] = nextDouble();
            sin[i] = Math.sin(Math.toRadians(a[i]));
            cos[i] = Math.cos(Math.toRadians(a[i]));
        }
        for (int i = 0; i < n; i++) {
            s = L;
            xx = x[i];
            yy = y[i];
            ii = i;
            dp[i][1 << i] = calc();
        }
        for (int mask = 0; mask < (1 << n); mask++) {
            for (int i = 0; i < n; i++) {
                if ((mask & (1 << i)) != 0) {
                    for (int j = 0; j < n; j++) {
                        if ((mask & (1 << j))==0) {
                            s = dp[i][mask];
                            xx = x[j];
                            yy = y[j];
                            ii = j;
                            dp[j][mask | (1 << j)] = Math.max(dp[j][mask | (1 << j)], calc());
                        }
                    }
                }
            }
        }
        double max = L;
        for (int mask = 0; mask < (1 << n); mask++) {
            for (int i = 0; i < n; i++) {
                max = Math.max(max, dp[i][mask]);
            }
        }
        if (max > R)
            max = R;
        pw.println(max-L);
        pw.close();
    }
    private static double calc() {
        double d = Math.sqrt((xx-s)*(xx-s)+yy*yy);
        double sinalfa = yy / d;
        double cosalfa = (xx-s) / d;
        double q = sin[ii]*cosalfa+cos[ii]*sinalfa;
        if (q < 0)
            return 1e9;
        double r = d * sin[ii] / q;
        return s+r;
    }
    private static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private static String next() throws IOException {
        while (st==null || !st.hasMoreTokens())
            st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }
}
/*
20 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
*/


import java.util.Scanner;

public class Main {

    static double sin[] = new double[91];
    static double cos[] = new double[91];

    static {
        for(int i = 0; i <= 90; ++i){
            sin[i] = Math.sin(Math.PI * i / 180);
            cos[i] = Math.cos(Math.PI * i / 180);
        }
    }

    static class Point{
        final int x;
        final int y;
        final int a;

        Point(int x, int y, int a) {
            this.x = x;
            this.y = y;
            this.a = a;
        }
    }

    public static void main(String[] args) {
        System.out.print(new Main().solve());
    }

    int n;
    int l;
    int r;
    Point[] points;

    public double nextEdge(double start, int index){
        Point point = points[index];
        double x1 = start - point.x;
        double y1 = - point.y;

        double y2 = x1 * sin[point.a] + y1 * cos[point.a];
        if (y2 >= 0){
            return r;
        }
        double x2 = x1 * cos[point.a] - y1 * sin[point.a];
        return point.x - x2 * point.y / y2;
    }

    public double solve() {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        l = sc.nextInt();
        r = sc.nextInt();
        points = new Point[n];
        for(int i = 0; i < n; ++i){
            points[i] = new Point(
                    sc.nextInt(),
                    sc.nextInt(),
                    sc.nextInt());
        }
        double[] distance = new double[1000001];
        for(int i = 0; i <= 1000000; ++i){
            distance[i] = l - 1;
        }
        int[] visited = new int[1000001];
        int count = 0;
        visited[count++] = 0;
        distance[0] = l;
        int start = 0;

        for(int c = 1; c <= n; ++c){
            int end = count;
            for(int i = start; i < end; ++i){
                int value = visited[i];
                for(int b = 0; b < n; ++b){
                    int mask = 1 << b;
                    if((value & mask) != 0) continue;
                    int cur = value | mask;
                    if(distance[cur] == l - 1)visited[count++] = cur;
                    double next = nextEdge(distance[value], b);
                    if(next >= r) return r - l;
                    if(next > distance[cur]) distance[cur] = next;
                }
            }
            start = end;
        }
        return distance[count - 1] - l;
    }
}