import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.Random;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
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 << 27);
        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);
            FastOutput out = new FastOutput(outputStream);
            DLinearCongruentialGenerator solver = new DLinearCongruentialGenerator();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class DLinearCongruentialGenerator {
        public int log(int x, int y) {
            int ans = 0;
            while (y != 0 && y % x == 0) {
                ans++;
                y /= x;
            }
            return ans;
        }

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int limit = (int) 2e6;
            IntegerMultiWayStack primeFactors = Factorization.factorizeRangePrime(limit);
            int[] cnts = new int[limit + 1];
            int[] times = new int[limit + 1];
            int[] xs = new int[n];
            Randomized.shuffle(xs);
            Arrays.sort(xs);
            SequenceUtils.reverse(xs);
            boolean[] retain = new boolean[n];
            in.populate(xs);
            for (int i = 0; i < n; i++) {
                int x = xs[i];
                if (cnts[x] == 0) {
                    retain[i] = true;
                    cnts[x] = 1;
                    times[x] = 1;
                    continue;
                }

                for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
                    int p = iterator.next();
                    int log = log(p, x - 1);
                    if (cnts[p] < log) {
                        cnts[p] = log;
                        times[p] = 0;
                    }
                    if (cnts[p] == log) {
                        times[p]++;
                    }
                }
            }

            Modular mod = new Modular(1e9 + 7);
            int prod = 1;
            for (int i = 1; i <= limit; i++) {
                for (int j = 0; j < cnts[i]; j++) {
                    prod = mod.mul(prod, i);
                }
            }

            for (int i = 0; i < n; i++) {
                int x = xs[i];
                boolean unique = false;
                if (retain[i]) {
                    if (cnts[x] == 1 && times[x] == 1) {
                        unique = true;
                    }
                } else {
                    for (IntegerIterator iterator = primeFactors.iterator(x - 1); iterator.hasNext(); ) {
                        int p = iterator.next();
                        int log = log(p, x - 1);
                        if (cnts[p] == log && times[p] == 1) {
                            unique = true;
                        }
                    }
                }
                if (!unique) {
                    prod = mod.plus(prod, 1);
                    break;
                }
            }

            out.println(prod);
        }

    }

    static class Modular {
        int m;

        public Modular(int m) {
            this.m = m;
        }

        public Modular(long m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public Modular(double m) {
            this.m = (int) m;
            if (this.m != m) {
                throw new IllegalArgumentException();
            }
        }

        public int valueOf(int x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return x;
        }

        public int valueOf(long x) {
            x %= m;
            if (x < 0) {
                x += m;
            }
            return (int) x;
        }

        public int mul(int x, int y) {
            return valueOf((long) x * y);
        }

        public int plus(int x, int y) {
            return valueOf(x + y);
        }

        public String toString() {
            return "mod " + m;
        }

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static boolean isMultiplicationOverflow(long a, long b, long limit) {
            if (limit < 0) {
                limit = -limit;
            }
            if (a < 0) {
                a = -a;
            }
            if (b < 0) {
                b = -b;
            }
            if (a == 0 || b == 0) {
                return false;
            }
            //a * b > limit => a > limit / b
            return a > limit / b;
        }

    }

    static class Randomized {
        public static void shuffle(int[] data) {
            shuffle(data, 0, data.length - 1);
        }

        public static void shuffle(int[] data, int from, int to) {
            to--;
            for (int i = from; i <= to; i++) {
                int s = nextInt(i, to);
                int tmp = data[i];
                data[i] = data[s];
                data[s] = tmp;
            }
        }

        public static int nextInt(int l, int r) {
            return RandomWrapper.INSTANCE.nextInt(l, r);
        }

    }

    static class RandomWrapper {
        private Random random;
        public static RandomWrapper INSTANCE = new RandomWrapper(new Random());

        public RandomWrapper() {
            this(new Random());
        }

        public RandomWrapper(Random random) {
            this.random = random;
        }

        public int nextInt(int l, int r) {
            return random.nextInt(r - l + 1) + l;
        }

    }

    static class IntegerMultiWayStack {
        private int[] values;
        private int[] next;
        private int[] heads;
        private int alloc;
        private int stackNum;

        public IntegerIterator iterator(final int queue) {
            return new IntegerIterator() {
                int ele = heads[queue];

                public boolean hasNext() {
                    return ele != 0;
                }

                public int next() {
                    int ans = values[ele];
                    ele = next[ele];
                    return ans;
                }
            };
        }

        private void doubleCapacity() {
            int newSize = Math.max(next.length + 10, next.length * 2);
            next = Arrays.copyOf(next, newSize);
            values = Arrays.copyOf(values, newSize);
        }

        public void alloc() {
            alloc++;
            if (alloc >= next.length) {
                doubleCapacity();
            }
            next[alloc] = 0;
        }

        public boolean isEmpty(int qId) {
            return heads[qId] == 0;
        }

        public IntegerMultiWayStack(int qNum, int totalCapacity) {
            values = new int[totalCapacity + 1];
            next = new int[totalCapacity + 1];
            heads = new int[qNum];
            stackNum = qNum;
        }

        public void addLast(int qId, int x) {
            alloc();
            values[alloc] = x;
            next[alloc] = heads[qId];
            heads[qId] = alloc;
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < stackNum; i++) {
                if (isEmpty(i)) {
                    continue;
                }
                builder.append(i).append(": ");
                for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) {
                    builder.append(iterator.next()).append(",");
                }
                if (builder.charAt(builder.length() - 1) == ',') {
                    builder.setLength(builder.length() - 1);
                }
                builder.append('\n');
            }
            return builder.toString();
        }

    }

    static class MinimumNumberWithMaximumFactors {
        private static int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};

        public static long[] maximumPrimeFactor(long n) {
            long[] ans = new long[2];
            ans[0] = 1;
            for (int i = 0; i < primes.length; i++) {
                if (DigitUtils.isMultiplicationOverflow(ans[0], primes[i], n)) {
                    break;
                }
                ans[0] *= primes[i];
                ans[1]++;
            }
            return ans;
        }

    }

    static class Factorization {
        public static IntegerMultiWayStack factorizeRangePrime(int n) {
            int maxFactorCnt = (int) MinimumNumberWithMaximumFactors.maximumPrimeFactor(n)[1];
            IntegerMultiWayStack stack = new IntegerMultiWayStack(n + 1, n * maxFactorCnt);
            boolean[] isComp = new boolean[n + 1];
            for (int i = 2; i <= n; i++) {
                if (isComp[i]) {
                    continue;
                }
                for (int j = i; j <= n; j += i) {
                    isComp[j] = true;
                    stack.addLast(j, i);
                }
            }
            return stack;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(int c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class SequenceUtils {
        public static void swap(int[] data, int i, int j) {
            int tmp = data[i];
            data[i] = data[j];
            data[j] = tmp;
        }

        public static void reverse(int[] data, int l, int r) {
            while (l < r) {
                swap(data, l, r);
                l++;
                r--;
            }
        }

        public static void reverse(int[] data) {
            reverse(data, 0, data.length - 1);
        }

    }

    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(int[] data) {
            for (int i = 0; i < data.length; i++) {
                data[i] = readInt();
            }
        }

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

    }

    static interface IntegerIterator {
        boolean hasNext();

        int next();

    }
}


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

public class D {

    public void solve() {
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            String s = in.nextToken().substring(4);
            out.println(getAns(s));
        }
    }

    private long getAns(String s) {
        long cur = 1988;
        for (int j = s.length() - 1; j >= 0; j--) {
            long last = 0, pow = 1;
            for (int t = j; t < s.length(); t++) {
                last = last * 10 + s.charAt(t) - '0';
                pow *= 10;
            }

            if (cur % pow < last) {
                cur = (cur / pow) * pow + last;
            } else {
                cur = (cur / pow + 1) * pow + last;
            }
        }
        return cur;
    }

    public void run() {
        in = new FastScanner();
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    FastScanner in;
    PrintWriter out;

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(String fileName) {
            try {
                br = new BufferedReader(new FileReader(fileName));
            } catch (FileNotFoundException e) {
            }
        }

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

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

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

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

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

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


import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import static java.lang.Integer.*;
import static java.lang.Double.*;
import java.lang.Math.*;

public class constanzes_machine {

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

	public void run() throws Exception {
		FastIO file = new FastIO();
//		char[] c = (" " + file.next()).toCharArray();
//		long[] dp = new long[c.length];
//		dp[0] = 1;
//		for (int i = 1; i < c.length; i++) {
//			if (c[i] == 'u' && c[i - 1] == 'u' || c[i] == 'n' && c[i - 1] == 'n') {
//				dp[i] = (dp[i - 1] + (i > 1 ? dp[i - 2] : 0)) % (long) (1e9+7);
//			}
//			else {
//				dp[i] = dp[i - 1] % (long) (1e9+7);
//			}
//		}
//		String s = new String(c);
//		if (s.contains("w") || s.contains("m")) {
//			System.out.println(0);
//		}
//		else {
//			System.out.println(dp[dp.length - 1] % (long) (1e9+7));
//		}
		System.out.println("INTERCAL");
		file.out.flush();
	}

	public static class FastIO {
		BufferedReader br;
		StringTokenizer st;
		PrintWriter out;

		public FastIO() {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

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

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

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

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

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

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

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

		void printf(String s, Object... o) {
			out.printf(s, o);
		}
	}

	public static long pow(long n, long p, long mod) {
		if (p == 0)
			return 1;
		if (p == 1)
			return n % mod;
		if (p % 2 == 0) {
			long temp = pow(n, p / 2, mod);
			return (temp * temp) % mod;
		} else {
			long temp = pow(n, (p - 1) / 2, mod);
			temp = (temp * temp) % mod;
			return (temp * n) % mod;

		}
	}

	public static long pow(long n, long p) {
		if (p == 0)
			return 1;
		if (p == 1)
			return n;
		if (p % 2 == 0) {
			long temp = pow(n, p / 2);
			return (temp * temp);
		} else {
			long temp = pow(n, (p - 1) / 2);
			temp = (temp * temp);
			return (temp * n);

		}
	}

	public static long gcd(long x, long y) {
		if (x == 0)
			return y;
		else
			return gcd(y % x, x);
	}

	public static boolean isPrime(int n) {
		if (n <= 1)
			return false;
		if (n <= 3)
			return true;

		if (n % 2 == 0 || n % 3 == 0)
			return false;

		for (int i = 5; i * i <= n; i = i + 6)
			if (n % i == 0 || n % (i + 2) == 0)
				return false;

		return true;
	}
}


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

import static java.lang.Math.*;

public class Main implements Runnable {

	int s;
	int c3 = 0, c4 = 0, c5 = 0;

	int naive(int s) {
		int bestk3 = -1, bestk4 = -1, bestk5 = -1;
		int bestf = Integer.MAX_VALUE / 2;
		for (int k3 = 0; k3 * c3 <= s; k3++) {
			for (int k4 = k3; k3 * c3 + k4 * c4 <= s; k4++) {
				int rem = s - k3 * c3 - k4 * c4;
				if (rem % c5 == 0) {
					int k5 = rem / c5;
					if (k5 < k4) {
						break;
					}
					int f = abs(c3 * k3 - c4 * k4) + abs(c4 * k4 - c5 * k5);
					//if (k3 == 1961) {
						System.out.println(k3 + " " + k4 + " " + k5 + " " + f);
					//}
					if (f < bestf) {
						bestk3 = k3;
						bestk4 = k4;
						bestk5 = k5;
						bestf = f;
					}
				}
			}
		}
		out.println(bestk3 + " " + bestk4 + " " + bestk5);
		out.println(bestf);
		return bestf;
	}

	int f(int k3, int k4) {
		int k5 = (s - k3 * c3 - k4 * c4) / c5;
		return abs(c3 * k3 - c4 * k4) + abs(c4 * k4 - c5 * k5);
	}

	void solve() throws Exception {
		int n = sc.nextInt();
		s = sc.nextInt();
		for (int i = 0; i < n; i++) {
			int mark = sc.nextInt();
			if (mark == 3) {
				c3++;
			} else if (mark == 4) {
				c4++;
			} else if (mark == 5) {
				c5++;
			}
		}
		//c3 = sc.nextInt();
		//c4 = sc.nextInt();
		//c5 = sc.nextInt();
		Random rnd = new Random();
		//c3 = rnd.nextInt(20) + 1;
		//c4 = rnd.nextInt(20) + 1;
		//c5 = rnd.nextInt(20) + 1;
		//out.println(c3 + " " + c4 + " " + c5);
		ArrayList<Integer>[] may = new ArrayList[c5];
		for (int i = 0; i < c5; i++) {
			may[i] = new ArrayList<Integer>();
			for (int j = 0; j < c5; j++) {
				if ((c3 * i + c4 * j) % c5 == s % c5) {
					may[i].add(j);
				}
			}
		}
		int bestk3 = -1, bestk4 = -1, bestk5 = -1;
		int bestf = Integer.MAX_VALUE / 2;
		for (int k3 = 0; k3 * c3 <= s; k3++) {
			if (may[k3 % c5].size() == 0) {
				continue;
			}
			ArrayList<Integer> cmay = may[k3 % c5];
			int ll = -1, rr = 500000;
			while (rr - ll > 1) {
				int mm = (ll + rr) / 2;
				int valm = cmay.get(mm % cmay.size()) + mm / cmay.size() * c5;
				if (valm < k3) {
					ll = mm;
				} else {
					rr = mm;
				}
			}
			int l = rr;
			//int vall = cmay.get(l % cmay.size()) + l / cmay.size() * c5;
			ll = -1;
			rr = 500000;
			while (rr - ll > 1) {
				int mm = (ll + rr) / 2;
				long valm = cmay.get(mm % cmay.size()) + mm / cmay.size() * c5;
				if ((s - k3 * c3 - valm * c4) >= c5 * valm) {
					ll = mm;
				} else {
					rr = mm;
				}
			}
			int r = ll;
			//int valr = cmay.get(r % cmay.size()) + r / cmay.size() * c5;
			if (l > r) {
				continue;
			}
			while (r - l >= 3) {
				int m1 = l + (r - l) / 3;
				int m2 = r - (r - l) / 3;
				int f1 = f(k3, cmay.get(m1 % cmay.size()) + m1 / cmay.size() * c5);
				int f2 = f(k3, cmay.get(m2 % cmay.size()) + m2 / cmay.size() * c5);
				if (f1 >= f2) {
					l = m1;
				} else {
					r = m2;
				}
			}
			for (int i = l; i <= r; i++) {
				int k4 = cmay.get(i % cmay.size()) + i / cmay.size() * c5;
				int k5 = (s - k3 * c3 - k4 * c4) / c5;
				int fi = f(k3, k4);
				if (fi < bestf) {
					bestk3 = k3;
					bestk4 = k4;
					bestk5 = k5;
					bestf = fi;
				}
			}
		}
		if (bestk3 != -1) {
			out.println(bestk3 + " " + bestk4 + " " + bestk5);
		} else {
			out.println(-1);
		}
		//out.println(bestf);
		//if (bestf != naive(s)) {
		//	throw new Exception();
		//}
	}

	BufferedReader in;
	PrintWriter out;
	FastScanner sc;

	static Throwable uncaught;

	@Override
	public void run() {
		try {
			//System.setOut(new PrintStream("test.txt"));
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			sc = new FastScanner(in);
			solve();
		} catch (Throwable t) {
			Main.uncaught = t;
		} finally {
			out.close();
		}
	}

	public static void main(String[] args) throws Throwable {
		Thread t = new Thread(null, new Main(), "", 128 * 1024 * 1024);
		t.start();
		t.join();
		if (uncaught != null) {
			throw uncaught;
		}
	}

}

class FastScanner {

	BufferedReader reader;
	StringTokenizer strTok;

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

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

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

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

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

}


import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.min;
import static java.lang.System.exit;

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

public class C {

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	static void solve() throws Exception {
		int n = nextInt();
		int m = nextInt();
		int a[] = new int[30];
		for (int i = 0; i < n; i++) {
			int cur = nextInt();
			for (int j = 0; j < 30; j++) {
				if ((cur & (1 << j)) != 0) {
					++a[j];
				}
			}
		}
		int b[] = new int[30];
		for (int i = 0; i < m; i++) {
			++b[nextInt()];
		}
		int ans = 0;
		for (int i = 0; i < 30; i++) {
			for (int j = i; j < 30; j++) {
				if (b[i] == 0) {
					break;
				}
				long have = (long) a[j] << (j - i);
				int take = (int) min(b[i], have);
				b[i] -= take;
				ans += take;
				have -= take;
				a[j] = (int) (have >> (j - i));
				for (int k = i; k < j; k++) {
					if ((have & (1 << (k - i))) != 0) {
						++a[k];
					}
				}
			}
			if (b[i] != 0) {
				break;
			}
		}
		out.print(ans);
	}

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

	static long nextLong() throws IOException {
		return parseLong(next());
	}

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

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

	public static void main(String[] args) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(new OutputStreamWriter(System.out));
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			exit(1);
		}
	}
}


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

import static java.lang.Math.*;

// Solution is at the bottom of code

public class ProblemB_010 implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	BufferedReader in;
	OutputWriter out;
	StringTokenizer tok = new StringTokenizer("");

	public static void main(String[] args){
		new Thread(null, new ProblemB_010(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

	void time(){
		timeEnd = System.currentTimeMillis();
		System.err.println("Time = " + (timeEnd - timeBegin));
	}

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

	String readString() throws IOException{
		while(!tok.hasMoreTokens()){
			try{
				tok = new StringTokenizer(in.readLine());
			}catch (Exception e){
				return null;
			}
		}

		return tok.nextToken(delim);
	}

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

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

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

	/////////////////////////////////////////////////////////////////

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

	int[] readIntArray(int size) throws IOException{
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

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

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

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

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		return new Point(readInt(), readInt());
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	class OutputWriter extends PrintWriter{

		final int DEFAULT_PRECISION = 12;

		int precision;
		String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

	boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	class Segment{

		int x;
		int left, right;

		Segment(int x, int left, int right){
			this.x = x;
			this.left = left;
			this.right = right;
		}

		int getWeight(){
			int sum = abs(x - xc) * (right - left + 1);

			if (right < yc){
				sum += ((yc - right) + (yc - left)) * (right - left + 1) / 2;
			}else if (left > yc){
				sum += ((-yc + right) + (-yc + left)) * (right - left + 1) / 2;
			}else{
				sum += (0 + (yc - left)) * (yc - left + 1) / 2;
				sum += (0 + (right - yc)) * (right - yc + 1) / 2;
			}

			return sum;
		}

		Segment getBest(int size){
			if (size > right - left + 1){
				return null;
			}

			if (right < yc){
				return new Segment(x, right - size + 1, right);
			}else if (left > yc){
				return new Segment(x, left, left + size - 1);
			}else{
				int yl = yc;
				int yr = yc;

				--size;

				int dl = yc - left;
				int dr = right - yc;

				int countRight = size / 2;
				int countLeft = size - countRight;

				if (dl < countLeft){
					countRight += countLeft - dl;
					countLeft = dl;
				}else if (dr < countRight){
					countLeft += countRight - dr;
					countRight = dr;
				}

				yl -= countLeft;
				yr += countRight;

//				for (int i = 0; i < size - 1; ++i){
//					if (i % 2 == 0){
//						if (yl > left){
//							--yl;
//						}else{
//							++yr;
//						}
//					}else{
//						if (yr < right){
//							++yr;
//						}else{
//							--yl;
//						}
//					}
//				}

				return new Segment(x, yl, yr);
			}
		}
	}

	int xc, yc;

	void solve() throws IOException{
		int n = readInt();
		int k = readInt();

		Set<Segment> set = new HashSet<ProblemB_010.Segment>();
		for (int i = 0; i < k; ++i){
			set.add(new Segment(i + 1, 1, k));
		}

		xc = (k + 1)/ 2;
		yc = (k + 1) / 2;

		while (n-- > 0){
			int size = readInt();

			int min = Integer.MAX_VALUE;
			Segment minS = null, minBest = null;

			for (Segment s: set){
				Segment best = s.getBest(size);

				if (best == null) continue;

				int w = best.getWeight();
				if (minS == null || min > w){
					min = w;
					minS = s;
					minBest = best;
				}else if (min == w){
					if (minBest.x > best.x){
						minS = s;
						minBest = best;
					}else if (minBest.x == best.x && minBest.left > best.left){
						minS = s;
						minBest = best;
					}
				}
			}

			if (minS == null){
				out.println(-1);
				continue;
			}

			set.remove(minS);

			if (minBest.left > minS.left){
				set.add(new Segment(minS.x, minS.left, minBest.left - 1));
			}
			if (minBest.right < minS.right){
				set.add(new Segment(minS.x, minBest.right + 1, minS.right));
			}

			out.println(minBest.x + " " + minBest.left + " " + minBest.right);
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.HashMap;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		int testCount = Integer.parseInt(in.next());
		for (int i = 1; i <= testCount; i++)
			solver.solve(i, in, out);
		out.close();
	}

	static class TaskE {
		final double eps = 1e-10;
		final long MAX_COORD = (int) 1e6;
		long MIN_X;
		long MIN_Y;
		long MAX_X;
		long MAX_Y;

		public void solve(int testNumber, FastScanner in, PrintWriter out) {
			int n = in.nextInt() - 1;
			long x0 = in.nextLong();
			long y0 = in.nextLong();
			MIN_X = -MAX_COORD - x0;
			MAX_X = +MAX_COORD - x0;
			MIN_Y = -MAX_COORD - y0;
			MAX_Y = +MAX_COORD - y0;
			PointLong[] p = new PointLong[n];
			for (int i = 0; i < n; i++) {
				long x = in.nextLong() - x0;
				long y = in.nextLong() - y0;
				p[i] = new PointLong(x, y);
			}
			Arrays.sort(p, (a, b) -> {
				boolean au = a.y > 0 || a.y == 0 && a.x > 0;
				boolean bu = b.y > 0 || b.y == 0 && b.x > 0;
				if (au != bu) {
					return au ? 1 : -1;
				}
				return -Long.signum(cross(a, b));
			});

			{
				int j = 0;
				for (int i = 0; i < n; i++) {
					j = Math.max(j, i + 1);
					while (cross(p[i], p[j % n]) > 0) {
						++j;
					}
					if (i != j % n && cross(p[i], p[j % n]) == 0) {
						out.println(0);
						return;
					}
					if (i != (i + 1) % n && cross(p[i], p[(i + 1) % n]) == 0) {
						out.println(0);
						return;
					}
				}
			}

			List<Line> lines = new ArrayList<>();
			{
				int j = 0;
				int best = -1;
				for (int i = 0; i < n; i++) {
					if (best >= 0 && cross(p[i], p[best]) <= 0) {
						best = -1;
					}
					if (i == j) {
						++j;
						if (j == n) j = 0;
					}
					while (cross(p[i], p[j]) > 0) {
						if (best < 0 || cross(p[best].sub(p[i]), p[j].sub(p[i])) > 0) {
							best = j;
						}
						++j;
						if (j == n) j = 0;
					}
					while (cross(p[i], p[j]) < 0) {
						--j;
						if (j < 0) j = n - 1;
					}
					if (best >= 0) {
						lines.add(new Line(p[i].toDoublePoint(), p[best].toDoublePoint()));
					}
				}
			}
			{
				int j = 0;
				for (int i = 0; i < n; i++) {
					++j;
					if (j == n) j = 0;
					if (cross(p[i], p[j]) > 0) {
						lines.add(new Line(p[i].toDoublePoint(), p[j].toDoublePoint()));
					}
				}
			}

//		List<Line> lines = new ArrayList<>();
//		for (int i = 0; i < n; i++) {
//			for (int j = 0; j < n; j++) {
//				if (cross(p[i], p[j]) > 0) {
//					lines.add(new Line(p[i].toDoublePoint(), p[j].toDoublePoint()));
//				}
//			}
//		}

			out.printf("%.15f\n", area(intersectSemiplanes(lines.toArray(new Line[0]))));
		}

		private double area(Point[] p) {
			if (p == null) {
				return 0;
			}
			double res = 0;
			for (int i = 0; i < p.length; i++) {
				int j = (i + 1) % p.length;
				res += (p[j].x - p[i].x) * (p[i].y + p[j].y);
			}
			return 0.5 * Math.abs(res);
		}

		private int compare(double a, double b) {
			if (Math.abs(a - b) < eps) {
				return 0;
			}
			return Double.compare(a, b);
		}

		private int sign(double x) {
			return compare(x, 0);
		}

		private double side(Point p, Line L) {
			return compare(p.x * L.a + p.y * L.b + L.c, 0);
		}

		private Point intersect(Line L1, Line L2) {
			double det = L1.a * L2.b - L2.a * L1.b;
			if (compare(det, 0) == 0) {
				return null;
			}
			double x = -(L1.c * L2.b - L2.c * L1.b) / det;
			double y = -(L1.a * L2.c - L2.a * L1.c) / det;
			return new Point(x, y);
		}

		private Point[] intersectSemiplanes(Line[] input) {
			List<Line> correctedInput = new ArrayList<>();
			for (Line L : input) {
				correctedInput.add(L);
			}
			Point[] corners = new Point[4];
			corners[0] = new Point(MIN_X, MIN_Y);
			corners[1] = new Point(MAX_X, MIN_Y);
			corners[2] = new Point(MAX_X, MAX_Y);
			corners[3] = new Point(MIN_X, MAX_Y);
			for (int i = 0; i < 4; i++) {
				correctedInput.add(new Line(corners[i], corners[(i + 1) % 4]));
			}

			Collections.sort(correctedInput, (L1, L2) -> {
				double ax = -L1.b, ay = L1.a;
				double bx = -L2.b, by = L2.a;
				boolean au = ay > 0 || (Math.abs(ay) < eps && ax > 0);
				boolean bu = by > 0 || (Math.abs(by) < eps && bx > 0);
				if (au != bu) {
					return au ? 1 : -1;
				}
				int s = -sign(ax * by - ay * bx);
				if (s != 0) {
					return s;
				}
				Point test = L1.anyPoint();
				return -sign(side(test, L2));
			});

			for (int i = correctedInput.size() - 1; i > 0; i--) {
				Line L1 = correctedInput.get(i);
				Line L2 = correctedInput.get(i - 1);
				double ax = -L1.b, ay = L1.a;
				double bx = -L2.b, by = L2.a;
				int d = sign(ax * bx + ay * by);
				int s = -sign(ax * by - ay * bx);
				if (d >= 0 && s == 0) {
					correctedInput.remove(i);
				}
			}

			Line[] borders = correctedInput.toArray(new Line[0]);
			List<Object> list = new ArrayList<>();
			list.add(borders[0]);
			list.add(intersect(borders[0], borders[1]));
			list.add(borders[1]);

			for (int i = 2; i < 2 * borders.length; i++) {
				Line L = borders[i % borders.length];
				while (list.size() >= 2) {
					Object o1 = list.get(list.size() - 2);
					Object o2 = list.get(list.size() - 1);
					if ((o1 instanceof Point) && (o2 instanceof Line)) {
						Point p = (Point) o1;
						if (side(p, L) > 0) {
							break;
						}
						list.remove(list.size() - 1);
						list.remove(list.size() - 1);
					} else {
						throw new AssertionError();
					}
				}
				Object obj = list.get(list.size() - 1);
				if (obj instanceof Line) {
					Line v = (Line) obj;
					if (sign(v.a * L.b - v.b * L.a) <= 0) {
						return null;
					}
					Point p = intersect(v, L);
					list.add(p);
					list.add(L);
				} else {
					throw new AssertionError();
				}
			}

			Map<Line, Integer> where = new HashMap<>();
			List<Line> allLines = new ArrayList<>();
			List<Point> res = new ArrayList<>();
			for (int i = 0; i < list.size(); i += 2) {
				Line L = (Line) list.get(i);
				allLines.add(L);
				if (where.containsKey(L)) {
					for (int j = where.get(L); j < allLines.size() - 1; j++) {
						res.add(intersect(allLines.get(j), allLines.get(j + 1)));
					}
					break;
				}
				where.put(L, i / 2);
			}
			return res.toArray(new Point[0]);
		}

		private long cross(PointLong a, PointLong b) {
			return a.x * b.y - a.y * b.x;
		}

		class Point {
			double x;
			double y;

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

			public String toString() {
				return "(" + x + " " + y + ")";
				//return String.format("(%.4f %.4f)", x, y);
			}

		}

		class Line {
			double a;
			double b;
			double c;
			Point anyPoint;

			Line(double a, double b, double c) {
				this.a = a;
				this.b = b;
				this.c = c;
			}

			Line(Point p1, Point p2) {
				a = p1.y - p2.y;
				b = p2.x - p1.x;
				c = -a * p1.x - b * p1.y;
				double len = Math.sqrt(a * a + b * b);
				a /= len;
				b /= len;
				c /= len;
				anyPoint = p1;
			}

			Point anyPoint() {
				if (anyPoint != null) {
					return anyPoint;
				}
				if (Math.abs(b) < eps) {
					if (Math.abs(a) < eps) {
						throw new AssertionError();
					}
					return new Point(-c / a, 0);
				}
				return new Point(0, -c / b);
			}

			public String toString() {
				return a + " " + b + " " + c;
			}

		}

		class PointLong {
			long x;
			long y;

			PointLong(long x, long y) {
				this.x = x;
				this.y = y;
			}

			PointLong sub(PointLong o) {
				return new PointLong(x - o.x, y - o.y);
			}

			Point toDoublePoint() {
				return new Point(x, y);
			}

			public String toString() {
				return "(" + x + " " + y + ")";
			}

		}

	}

	static class FastScanner {
		private BufferedReader in;
		private StringTokenizer st;

		public FastScanner(InputStream stream) {
			in = new BufferedReader(new InputStreamReader(stream));
		}

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

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

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

	}
}


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

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

    static class TaskD {
        final int MOD = (int) 1e9 + 7;
        int invMod2 = invmod(2);
        private final int sz = 22;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int l = in.nextInt(), r = in.nextInt();

            int ans = solve(r) - solve(l - 1);
            if (ans < 0) ans += MOD;

            out.println(ans);
        }

        private int pow(int x, int y) {
            int ret = 1;
            for (; y > 0; y >>= 1) {
                if ((y & 1) != 0) ret = (int) ((long) ret * x % MOD);
                x = (int) ((long) x * x % MOD);
            }
            return ret;
        }

        private int invmod(int x) {
            return pow(x, MOD - 2);
        }

        private boolean good(int a, int b) {
            return !(a == b ||
                    a == 0 && b == 3 ||
                    a == 3 && b == 0 ||
                    a == 1 && b == 2 ||
                    a == 2 && b == 1);
        }

        private boolean good(int a, int b, int c) {
            return !(a == 1 && b == 0 && c == 2 ||
                    a == 2 && b == 0 && c == 1);
        }

        private int solve(int n) {
            if (n <= 1) return 4 * n;

            Matrix A = new Matrix();
            for (int i = 0; i <= 4; ++i) {
                for (int j = 0; j < 4; ++j) {
                    for (int k = 0; k < 4; ++k) {
                        if (!good(i, j) || !good(j, k) || !good(i, j, k))
                            continue;
                        A.a[5 * k + j][5 * j + i] = 1;
                    }
                }
            }
            for (int i = 0; i < 4; ++i) {
                A.a[5 * i + 4][20] = 1;
            }
            A.a[21][21] = 1;
            for (int i = 0; i < 4; ++i) {
                for (int j = 0; j <= 4; ++j) {
                    if (good(i, j)) {
                        A.a[21][5 * i + j] = 1;
                    }
                }
            }

            int ans = pow(A, n + 1).a[21][20];
            if (n >= 2) {
                int add = pow(A, (n + 1) / 2 + 1).a[21][20];
                ans = (ans + add) % MOD;
                ans = (int) ((long) ans * invMod2 % MOD);
            }

            return ans;
        }

        private Matrix pow(Matrix x, int y) {
            Matrix ret = new Matrix();
            for (int i = 0; i < sz; ++i)
                ret.a[i][i] = 1;
            for (; y > 0; y >>= 1) {
                if ((y & 1) != 0) ret = ret.mul(x);
                x = x.mul(x);
            }
            return ret;
        }

        private class Matrix {
            int[][] a;

            Matrix() {
                a = new int[sz][sz];
            }

            public Matrix mul(Matrix o) {
                Matrix r = new Matrix();
                for (int i = 0; i < sz; ++i) {
                    for (int j = 0; j < sz; ++j) {
                        for (int k = 0; k < sz; ++k) {
                            r.a[i][j] = (int) ((r.a[i][j] +
                                    (long) a[i][k] * o.a[k][j]) % MOD);
                        }
                    }
                }
                return r;
            }

        }

    }

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

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

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

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

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

            return res.toString();
        }

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

    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    Scanner in;
    PrintWriter out;

    void setIn(String fI) {

        try {
            in = new Scanner(new FileInputStream(new File(fI)));
        } catch (FileNotFoundException e) {
            throw new Error(e);
        }
    }

    void setIn() {
        in = new Scanner(System.in);
    }

    void setOut(String fO) {
        try {
            out = new PrintWriter(new FileWriter(fO));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    void setOut() {
        out = new PrintWriter(System.out);
    }

    class Scanner {
        StringTokenizer st;
        BufferedReader in;
        String del;

        Scanner(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
            st = null;
            del = " \t\n\r\f";
        }

        void setDelimiters(String del) {
            this.del = del;
        }

        String next() {
            if (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine(), del);
            }
            return st.nextToken();
        }

        String nextLine() {
            try {
                st = null;
                return in.readLine();
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        boolean hasNext() {
            try {
                return in.ready() || (st != null && st.hasMoreTokens());
            } catch (IOException e) {
                throw new Error(e);
            }
        }

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

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

        BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        BigDecimal nextBigDecimal() {
            return new BigDecimal(next());
        }

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

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

    void run() {
        setIn();
        setOut();
        try {
            solve();
        } finally {
            out.close();
        }
    }

    class Point {
        int x;
        int y;

        Point(int X, int Y) {
            x = X;
            y = Y;
        }

        @Override
        public boolean equals(Object o) {
            Point p = (Point) o;
            return p.x == x && y == p.y;
        }

        @Override
        public int hashCode() {
            return 31 * x + y;
        }
    }

    class FoundException extends Exception {

    }

    boolean isMagic(int[][] a) {
        int s = 0;
        for (int i = 0; i < a.length; i++) {
            s += a[0][i];
        }
        int n = a.length;
        int s1 = 0;
        int s2 = 0;
        for (int i = 0; i < n; i++) {
            int curS = 0;
            int curS2 = 0;
            s1 += a[i][i];
            s2 += a[i][n - 1 - i];
            for (int j = 0; j < n; j++) {
                curS += a[i][j];
                curS2 += a[j][i];
            }
            if (curS != s || curS2 != s)
                return false;
        }
        return s1 == s && s2 == s;
    }

    int[][] a;

    void out(int[][] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length; j++) {
                out.print(a[i][j] + " ");
            }
            out.println();
        }
        out.println();
    }

    void go(int x, int y, HashMap<Integer, Integer> numb) throws FoundException {
        if (y == 0 && x == a.length) {
            if (isMagic(a)) {
                int n = a.length;
                int sum = 0;
                for (int i = 0; i < n; i++) {
                    sum += a[0][i];
                }
                out.println(sum);
                for (int i = 0; i < a.length; i++) {
                    for (int j = 0; j < n; j++) {
                        out.print(a[i][j] + " ");
                    }
                    out.println();
                }
                throw new FoundException();
            }
        }

        // out(a);
        int prevX = x;
        int prevY = y;
        y++;
        if (y == a.length) {
            x++;
            y = 0;
        }

        for (int key : numb.keySet()) {
            if (numb.get(key) != 0) {
                numb.put(key, numb.get(key) - 1);
                a[prevX][prevY] = key;
                go(x, y, numb);
                numb.put(key, numb.get(key) + 1);
            }
        }
    }

    void solve() {
        int n = in.nextInt();
        int[] b = in.nextIntArray(n * n);
        HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
        for (int i = 0; i < n * n; i++) {
            if (!numbers.containsKey(b[i]))
                numbers.put(b[i], 1);
            else
                numbers.put(b[i], numbers.get(b[i]) + 1);
        }
        a = new int[n][n];
        try {
            go(0, 0, numbers);
        } catch (FoundException e) {
            // good
        }
    }
}


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

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

    static class G1PlaylistForPolycarpEasyVersion {
        private int songsCount;
        private int totalDuration;
        private G1PlaylistForPolycarpEasyVersion.Song songs;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            songsCount = in.nextInt();
            totalDuration = in.nextInt();

            songs = new G1PlaylistForPolycarpEasyVersion.Song[songsCount];

            for (int i = 0; i < songsCount; i++) {
                songs[i] = new G1PlaylistForPolycarpEasyVersion.Song(in.nextInt(), in.nextInt());
            }

            int ret = 0;
            int chosenSongs = 0;

            for (int i = 0; i < songsCount; i++) {
                chosenSongs = 1 << i;
                ret += search(totalDuration - songs[i].duration, songs[i], chosenSongs);
            }

            out.println(ret);
        }

        private int search(int timeLeft, G1PlaylistForPolycarpEasyVersion.Song prev, int chosen) {
            if (timeLeft < 0) {
                return 0;
            }

            if (timeLeft == 0) {
                return 1;
            }

            int ret = 0;

            for (int i = 0; i < songsCount; i++) {
                if (((1 << i) & chosen) == 0 && songs[i].genre != prev.genre) {
                    ret += search(timeLeft - songs[i].duration, songs[i], chosen | 1 << i);
                }
            }

            return ret;
        }

        static class Song {
            public int duration;
            public int genre;

            public Song(int duration, int genre) {
                this.duration = duration;
                this.genre = genre;
            }

        }

    }

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

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

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

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

    }
}


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

public class E {

	static class Point {
		int x, y, id;

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

	static Comparator<Point> byAngle = new Comparator<E.Point>() {

		@Override
		public int compare(Point o1, Point o2) {
			return -Long.compare((long) o1.x * o2.y, (long) o2.x * o1.y);
		}
	};

	void submit() {
		int r = nextInt();
		int q = nextInt();

		int[][] qs = new int[q][3];
		int n = 0;

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

			qs[i][0] = nextInt();
			if (qs[i][0] == 1) {
				n++;
				qs[i][1] = nextInt();
				qs[i][2] = nextInt();
			} else if (qs[i][0] == 2) {
				qs[i][1] = nextInt() - 1;
			} else if (qs[i][0] == 3) {
				qs[i][1] = nextInt() - 1;
				qs[i][2] = nextInt() - 1;
			}
		}

		int[] xs, ys;

		Point[] px, py;

		int[] treeXIdx = new int[n];
		int[] askX;

		{
			Point[] a = new Point[n];
			int ptr = 0;
			for (int i = 0; i < q; i++) {
				if (qs[i][0] == 1) {
					a[ptr] = new Point(qs[i][1] - r, qs[i][2], ptr);
					ptr++;
				}
			}

			Arrays.sort(a, byAngle);

			for (int i = 0; i < n; i++) {
				treeXIdx[a[i].id] = i;
			}

			px = makeUnique(a, byAngle);
			xs = new int[n];

			for (Point p : a) {
				xs[p.id] = Arrays.binarySearch(px, p, byAngle);
			}

			askX = new int[px.length];
			askX[px.length - 1] = n;

			int pptr = px.length - 1;
			for (int i = n - 2; i >= 0; i--) {
				if (byAngle.compare(a[i], a[i + 1]) != 0) {
					askX[--pptr] = i + 1;
				}
			}

			if (pptr != 0) {
				throw new AssertionError();
			}
		}

		{
			Point[] a = new Point[n];
			int ptr = 0;
			for (int i = 0; i < q; i++) {
				if (qs[i][0] == 1) {
					a[ptr] = new Point(qs[i][1] + r, qs[i][2], ptr);
					ptr++;
				}
			}

			py = makeUnique(a, byAngle.reversed());
			ys = new int[n];

			for (Point p : a) {
				ys[p.id] = Arrays.binarySearch(py, p, byAngle.reversed());
			}
		}

//		System.err.println(Arrays.toString(xs));
//		System.err.println(Arrays.toString(ys));

		int ptr = 0;

		root = new Node(0, n);

		for (int i = 0; i < q; i++) {
			if (qs[i][0] == 1) {
				root.set(treeXIdx[ptr], ys[ptr]);
				ptr++;
			} else if (qs[i][0] == 2) {
				int what = qs[i][1];
				root.set(treeXIdx[what], Integer.MAX_VALUE);
			} else if (qs[i][0] == 3) {
				int p1 = qs[i][1];
				int p2 = qs[i][2];
				root.set(treeXIdx[p1], Integer.MAX_VALUE);
				root.set(treeXIdx[p2], Integer.MAX_VALUE);

				int qx = Math.max(xs[p1], xs[p2]);
				int qy = Math.max(ys[p1], ys[p2]);

				int ret = root.get(0, askX[qx]);

				boolean ans = ret > qy && !isInside(r, px[qx], py[qy]);
				out.println(ans ? "YES" : "NO");

				root.set(treeXIdx[p1], ys[p1]);
				root.set(treeXIdx[p2], ys[p2]);
			}
		}
	}

	TreeSet<Integer>[] set;
	Node root;

	static class Node {
		int l, r;
		Node left, right;

		int val;

		public Node(int l, int r) {
			this.l = l;
			this.r = r;
			val = Integer.MAX_VALUE;

			if (r - l > 1) {
				int m = (l + r) >> 1;
				left = new Node(l, m);
				right = new Node(m, r);
			}
		}

		void set(int x, int y) {
			if (r - l == 1) {
				val = y;
				return;
			}
			(x < left.r ? left : right).set(x, y);
			val = Math.min(left.val, right.val);
		}

		int get(int ql, int qr) {
			if (ql <= l && r <= qr) {
				return val;
			}
			if (l >= qr || ql >= r) {
				return Integer.MAX_VALUE;
			}
			return Math.min(left.get(ql, qr), right.get(ql, qr));
		}
	}

	boolean isInside(int r, Point vl, Point vr) {
		return (long) vl.x * vr.x + (long) vl.y * vr.y < 0;
	}

	Point[] makeUnique(Point[] a, Comparator<Point> cmp) {
		a = a.clone();
		Arrays.sort(a, cmp);

		int sz = 1;
		for (int i = 1; i < a.length; i++) {
			if (cmp.compare(a[i], a[sz - 1]) != 0) {
				a[sz++] = a[i];
			}
		}
		return Arrays.copyOf(a, sz);
	}

	void preCalc() {

	}

	void stress() {

	}

	void test() {

	}

	E() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		preCalc();
		submit();
		// stress();
		// test();
		out.close();
	}

	static final Random rng = new Random();

	static int rand(int l, int r) {
		return l + rng.nextInt(r - l + 1);
	}

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

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;

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

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

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

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

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


import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.fill;

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

public class G {

	interface IntComparator {
		public int compare(int o1, int o2);
	}

	static void sort(int a[], int n, IntComparator cmp) {
		if (n == 0) {
			return;
		}
		for (int i = 1; i < n; i++) {
			int j = i;
			int ca = a[i];
			do {
				int nj = (j - 1) >> 1;
				int na = a[nj];
				if (cmp.compare(na, ca) >= 0) {
					break;
				}
				a[j] = na;
				j = nj;
			} while (j != 0);
			a[j] = ca;
		}
		int ca = a[0];
		for (int i = n - 1; i > 0; i--) {
			int j = 0;
			while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) {
				j <<= 1;
				j += (cmp.compare(a[j + 1], a[j + 2]) < 0) ? 2 : 1;
			}
			if ((j << 1) + 2 == i) {
				j = (j << 1) + 1;
			}
			int na = a[i];
			a[i] = ca;
			ca = na;
			while (j != 0 && cmp.compare(a[j], ca) < 0) {
				j = (j - 1) >> 1;
			}
			while (j != 0) {
				na = a[j];
				a[j] = ca;
				ca = na;
				j = (j - 1) >> 1;
			}
		}
		a[0] = ca;
	}

	static int n, k, a[], sum, move[], moveOffset, defer[], deferCnt, derefFirst[];

	static void doMove(int pos) {
		if (a[pos] < (move[(pos + 1) % n] - moveOffset) || a[(pos + k - 1) % n] < -(move[(pos + k - 1) % n] - moveOffset)) {
			if (deferCnt == 0) {
				derefFirst = new int[k - 1];
				for (int i = 0; i < k - 1; i++) {
					derefFirst[i] = move[(pos + i + 1) % n] - moveOffset;
					move[(pos + i + 1) % n] = moveOffset;
				}
			}
			defer[deferCnt++] = pos;
			return;
		}
		for (int i = 0; i < k - 1; i++) {
			int m = move[(pos + i + 1) % n] - moveOffset;
			a[(pos + i) % n] -= m;
			a[(pos + i + 1) % n] += m;
			move[(pos + i + 1) % n] = moveOffset;
		}
		out.print(pos + 1);
		for (int i = 0; i < k; i++) {
			out.print(" " + a[(pos + i) % n]);
		}
		out.println();
		if (deferCnt > 0) {
			if (--deferCnt == 0) {
				pos = defer[0];
				for (int i = 0; i < k - 1; i++) {
					int m = derefFirst[i];
					a[(pos + i) % n] -= m;
					a[(pos + i + 1) % n] += m;
				}
			} else {
				doMove(defer[deferCnt]);
			}
		}
	}

	static void solve() throws Exception {
		n = scanInt();
		k = scanInt();
		a = new int[n];
		sum = 0;
		for (int i = 0; i < n; i++) {
			sum += a[i] = scanInt();
		}
		sum /= n;
		move = new int[n];
		int idx[] = new int[n];
		for (int i = 0; i < n - 1; i++) {
			move[i + 1] = move[i] + a[i] - sum;
			idx[i] = i;
		}
		idx[n - 1] = n - 1;
		sort(idx, n, new IntComparator() {
			public int compare(int o1, int o2) {
				return move[o1] != move[o2] ? move[o1] - move[o2] : o1 - o2;
			}
		});
		int ans = (n + k - 2) / (k - 1), ansStart = -1;
		int maxChain[] = new int[n], curNext[] = new int[k - 1];
		fill(curNext, -1);
		for (int i = 0, j; i < n; i = j) {
			for (j = i + 1; j < n && move[idx[j]] == move[idx[i]]; j++) { }
			for (int ii = j - 1; ii >= i; ii--) {
				int ci = idx[ii], ni = curNext[(ci + 1) % (k - 1)];
//				System.err.println(ci + " " + ni);
				maxChain[ci] = ni < 0 ? 1 : 1 + maxChain[ni];
				int cans = (n - maxChain[ci] + k - 2) / (k - 1);
				if (cans < ans) {
					ans = cans;
					ansStart = ci;
				}
				curNext[ci % (k - 1)] = ci;
			}
			for (int ii = i; ii < j; ii++) {
				curNext[idx[ii] % (k - 1)] = -1;
			}
		}
//		System.err.println(Arrays.toString(maxChain));
		out.println(ans);
		defer = new int[n];
		deferCnt = 0;
//		System.err.println(ans + " " + ansStart + " " + sum);
		if (ansStart < 0) {
			moveOffset = 0;
			for (int i = 0; i < ans; i++) {
				doMove(i * (k - 1));
			}
		} else {
			moveOffset = move[ansStart];
//			System.err.println(Arrays.toString(move) + " " + moveOffset);
			for (int i = 0, pos = ansStart; i < ans; i++) {
				while (move[(pos + 1) % n] == moveOffset) {
					pos = (pos + 1) % n;
				}
//				System.err.println(pos);
				doMove(pos);
//				System.err.println(Arrays.toString(a));
				pos = (pos + k - 1) % n;
			}
		}
		if (deferCnt != 0) {
			throw new AssertionError();
		}
	}

	static int scanInt() throws IOException {
		return parseInt(scanString());
	}

	static long scanLong() throws IOException {
		return parseLong(scanString());
	}

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

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	public static void main(String[] args) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			exit(1);
		}
	}
}


import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class StringPlay {
    public static final int UNREACHABLE = 1000;

    FastScanner in;
    PrintWriter out;

    public void solve() throws IOException {
        int n = in.nextInt();
        char[][] t = new char[n][n];
        for (int i = 0; i < n; i++) {
            t[i] = in.next().toCharArray();
        }

        int[] curr = new int[1 << n];
        Arrays.fill(curr, UNREACHABLE);
        curr[1 << (n - 1)] = getValue(t[n - 1][n - 1]);

        int[] next = new int[1 << n];

        for (int layer = 2 * n - 2; layer > 0; layer--) {
            boolean first = layer % 2 == 0;
            Arrays.fill(next, UNREACHABLE);

            for (int state = 0; state < curr.length; state++) {
                if (curr[state] == UNREACHABLE) {
                    continue;
                }

                int[] nextMask = new int['z' - 'a' + 1];
                for (int row = 0; row < n; row++) {
                    int col = layer - row;
                    if (col < 0 || col > n - 1) {
                        continue;
                    }
                    int bit = 1 << col;
                    if ((state & bit) == 0) {
                        continue;
                    }

                    if (col > 0) {
                        int ch = t[row][col - 1] - 'a';
                        nextMask[ch] += (1 << (col - 1));
                    }
                    if (row > 0) {
                        int ch = t[row - 1][col] - 'a';
                        nextMask[ch] += (1 << col);
                    }
                }

                for (int i = 0; i < nextMask.length; i++) {
                    int add = getValue((char) ('a' + i));
                    int mask = nextMask[i];
                    if (mask == 0) {
                        continue;
                    }

                    if (next[mask] == UNREACHABLE) {
                        next[mask] = curr[state] + add;
                    }
                    if (first) {
                        next[mask] = Math.max(next[mask], curr[state] + add);
                    } else {
                        next[mask] = Math.min(next[mask], curr[state] + add);
                    }
                }
            }

            int[] tmp = next;
            next = curr;
            curr = tmp;
        }

        if (curr[1] == 0) {
            out.println("DRAW");
        } else {
            out.println(curr[1] > 0 ? "FIRST" : "SECOND");
        }
    }

    private int getValue(char c) {
        return c != 'a' ? c == 'b' ? -1 : 0 : 1;
    }

    public void run() {
        try {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);

            solve();

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

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

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

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

    public static void main(String[] arg) {
        new StringPlay().run();
    }
}


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

public class MainD {
	static StdIn in = new StdIn();
	static PrintWriter out = new PrintWriter(System.out);
	static long p;
	static List<Long> pFs = new ArrayList<Long>();
	static long[] fact1;
	static int[][] fact2;

	public static void main(String[] args) {
		int n=in.nextInt();
		p=in.nextLong();
		int l=in.nextInt(), r=in.nextInt();
		long p2=p;
		for(int i=2; i*i<=p2; ++i) {
			if(p2%i==0) {
				while(p2%i==0)
					p2/=i;
				pFs.add((long)i);
			}
		}
		if(p2>1)
			pFs.add(p2);
		fact1 = new long[2*n+1];
		fact2 = new int[pFs.size()][2*n+1];
		fact1[0]=1;
		for(int i=1; i<=2*n; ++i) {
			long a=i;
			for(int j=0; j<pFs.size(); ++j) {
				fact2[j][i]=fact2[j][i-1];
				while(a%pFs.get(j)==0) {
					a/=pFs.get(j);
					++fact2[j][i];
				}
			}
			fact1[i]=fact1[i-1]*a%p;
		}
		long ans1=0;
		for(int i=0; i<=n; ++i) {
			ans1=(ans1+nCk(n, i)*(nCk(n-i, (n-i)/2-(l+l*(n-i+1)%2)/2)-nCk(n-i, (n-i)/2-(r-(r+1)*(n-i)%2+2)/2)+p))%p;
			//out.println(ans1+" "+nCk(n, i)+" "+nCk(n-i, (n-i)/2-l/2));
		}
		out.println(ans1);
		out.close();
	}

	static long nCk(int n, int k) {
		if(k>n||k<0)
			return 0;
		long r=fact1[n]*modI(fact1[k])%p*modI(fact1[n-k])%p;
		for(int i=0; i<pFs.size(); ++i)
			r=r*expM(pFs.get(i), fact2[i][n]-fact2[i][k]-fact2[i][n-k])%p;
		return r;
	}

	static long expM(long b, int e) {
		if(e==0)
			return 1;
		if(e%2==1)
			return b*expM(b*b%p, e/2)%p;
		return expM(b*b%p, e/2);
    }

	static long modI(long a) {
        long m0 = p, t, q, x0 = 0, x1 = 1;
        while(a>1) {
            q = a / m0;
            t = m0;
            m0 = a % m0;
            a = t;
            t = x0;
            x0 = x1 - q * x0;
            x1 = t;
        }
        if(x1<0)
			x1 += p;
        return x1;
    }

	interface Input {
		public String next();
		public String nextLine();
		public int nextInt();
		public long nextLong();
		public double nextDouble();
	}
	static class StdIn implements Input {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;
		public StdIn() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public StdIn(InputStream in) {
			try{
				din = new DataInputStream(in);
			} catch(Exception e) {
				throw new RuntimeException();
			}
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public String next() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == ' ' || c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c=read();
			}
			return s.toString();
		}
		public String nextLine() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c = read();
			}
			return s.toString();
		}
		public int nextInt() {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}
		public int[] readIntArray(int n) {
			int[] ar = new int[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextInt();
			return ar;
		}
		public long nextLong() {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
		public long[] readLongArray(int n) {
			long[] ar = new long[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextLong();
			return ar;
		}
		public double nextDouble() {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (c == '.')
				while ((c = read()) >= '0' && c <= '9')
					ret += (c - '0') / (div *= 10);
			if (neg)
				return -ret;
			return ret;
		}
		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}
		private byte read() {
			try{
				if (bufferPointer == bytesRead)
					fillBuffer();
				return buffer[bufferPointer++];
			} catch(IOException e) {
				throw new RuntimeException();
			}
		}
		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
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 << 27);
        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);
            FastOutput out = new FastOutput(outputStream);
            GXMouseInTheCampus solver = new GXMouseInTheCampus();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class GXMouseInTheCampus {
        LongHashMap mu = new LongHashMap(100000, false);
        LongHashMap euler = new LongHashMap(100000, false);
        long[] primes;

        {
            mu.put(1, 1);
            euler.put(1, 1);
        }

        public long oneOfPrimeFactor(long x) {
            for (long p : primes) {
                if (x % p == 0) {
                    return p;
                }
            }
            return x;
        }

        public void populate(long x) {
            long factor = oneOfPrimeFactor(x);
            long cnt = 0;
            long y = x;
            while (y % factor == 0) {
                cnt++;
                y /= factor;
            }
            if (cnt > 1) {
                mu.put(x, 0);
            } else {
                mu.put(x, -mu(y));
            }
            euler.put(x, euler(y) * (x / y - x / y / factor));
        }

        public long mu(long x) {
            long ans = mu.getOrDefault(x, -1);
            if (ans == -1) {
                populate(x);
                ans = mu.get(x);
            }
            return ans;
        }

        public long euler(long x) {
            long ans = euler.getOrDefault(x, -1);
            if (ans == -1) {
                populate(x);
                ans = euler.get(x);
            }
            return ans;
        }

        public void solve(int testNumber, FastInput in, FastOutput out) {
            long m = in.readLong();
            long x = in.readLong();

            primes = Factorization.factorizeNumberPrime(m).toArray();
            LongList allFactorOfM = new LongList(20000);
            LongList tmpList = new LongList(20000);
            collect(allFactorOfM, m, 0);
            LongPower power = new LongPower(ILongModular.getInstance(m));

            long total = 1;
            for (int i = 0; i < allFactorOfM.size(); i++) {
                long g = allFactorOfM.get(i);
                if (g == m) {
                    continue;
                }
                long mg = m / g;
                tmpList.clear();
                collect(tmpList, mg, 0);
                long cnt = 0;
                for (int j = tmpList.size() - 1; j >= 0; j--) {
                    long t = tmpList.get(j);
                    cnt += mu(t) * ((m - 1) / (t * g));
                }

                tmpList.clear();
                long euler = euler(mg);
                LongList primeFactors = Factorization.factorizeNumberPrime(euler);

                long n = euler;

                for (int j = 0; j < primeFactors.size(); j++) {
                    long p = primeFactors.get(j);
                    while (n % p == 0 && power.pow(x, n / p) % mg == 1) {
                        n /= p;
                    }
                }

                if (cnt % n != 0) {
                    throw new IllegalStateException();
                }
                total += cnt / n;
            }

            out.println(total);
        }

        public void collect(LongList list, long x, int i) {
            if (i == primes.length) {
                list.add(x);
                return;
            }
            collect(list, x, i + 1);
            while (x % primes[i] == 0) {
                x /= primes[i];
                collect(list, x, i + 1);
            }
        }

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long round(double x) {
            if (x >= 0) {
                return (long) (x + 0.5);
            } else {
                return (long) (x - 0.5);
            }
        }

        public static long mod(long x, long mod) {
            x %= mod;
            if (x < 0) {
                x += mod;
            }
            return x;
        }

        public static long mulMod(long a, long b, long mod) {
            long k = DigitUtils.round((double) a / mod * b);
            return DigitUtils.mod(a * b - k * mod, mod);
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(long c) {
            cache.append(c);
            println();
            return this;
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class LongPower {
        final ILongModular modular;

        public LongPower(ILongModular modular) {
            this.modular = modular;
        }

        public long pow(long x, long n) {
            if (n == 0) {
                return 1;
            }
            long r = pow(x, n >> 1);
            r = modular.mul(r, r);
            if ((n & 1) == 1) {
                r = modular.mul(r, x);
            }
            return r;
        }

    }

    static class Factorization {
        public static LongList factorizeNumberPrime(long x) {
            LongList ans = new LongList();
            for (long i = 2; i * i <= x; i++) {
                if (x % i != 0) {
                    continue;
                }
                ans.add(i);
                while (x % i == 0) {
                    x /= i;
                }
            }
            if (x > 1) {
                ans.add(x);
            }
            return ans;
        }

    }

    static class LongHashMap {
        private int[] slot;
        private int[] next;
        private long[] keys;
        private long[] values;
        private int alloc;
        private boolean[] removed;
        private int mask;
        private int size;
        private boolean rehash;

        public LongHashMap(int cap, boolean rehash) {
            this.mask = (1 << (32 - Integer.numberOfLeadingZeros(cap - 1))) - 1;
            slot = new int[mask + 1];
            next = new int[cap + 1];
            keys = new long[cap + 1];
            values = new long[cap + 1];
            removed = new boolean[cap + 1];
            this.rehash = rehash;
        }

        private void doubleCapacity() {
            int newSize = Math.max(next.length + 10, next.length * 2);
            next = Arrays.copyOf(next, newSize);
            keys = Arrays.copyOf(keys, newSize);
            values = Arrays.copyOf(values, newSize);
            removed = Arrays.copyOf(removed, newSize);
        }

        public void alloc() {
            alloc++;
            if (alloc >= next.length) {
                doubleCapacity();
            }
            next[alloc] = 0;
            removed[alloc] = false;
            size++;
        }

        private void rehash() {
            int[] newSlots = new int[Math.max(16, slot.length * 2)];
            int newMask = newSlots.length - 1;
            for (int i = 0; i < slot.length; i++) {
                if (slot[i] == 0) {
                    continue;
                }
                int head = slot[i];
                while (head != 0) {
                    int n = next[head];
                    int s = hash(keys[head]) & newMask;
                    next[head] = newSlots[s];
                    newSlots[s] = head;
                    head = n;
                }
            }
            this.slot = newSlots;
            this.mask = newMask;
        }

        private int hash(long x) {
            int h = Long.hashCode(x);
            return h ^ (h >>> 16);
        }

        public void put(long x, long y) {
            put(x, y, true);
        }

        public void put(long x, long y, boolean cover) {
            int h = hash(x);
            int s = h & mask;
            if (slot[s] == 0) {
                alloc();
                slot[s] = alloc;
                keys[alloc] = x;
                values[alloc] = y;
            } else {
                int index = findIndexOrLastEntry(s, x);
                if (keys[index] != x) {
                    alloc();
                    next[index] = alloc;
                    keys[alloc] = x;
                    values[alloc] = y;
                } else if (cover) {
                    values[index] = y;
                }
            }
            if (rehash && size >= slot.length) {
                rehash();
            }
        }

        public long getOrDefault(long x, long def) {
            int h = hash(x);
            int s = h & mask;
            if (slot[s] == 0) {
                return def;
            }
            int index = findIndexOrLastEntry(s, x);
            return keys[index] == x ? values[index] : def;
        }

        public long get(long x) {
            return getOrDefault(x, 0);
        }

        private int findIndexOrLastEntry(int s, long x) {
            int iter = slot[s];
            while (keys[iter] != x) {
                if (next[iter] != 0) {
                    iter = next[iter];
                } else {
                    return iter;
                }
            }
            return iter;
        }

        public LongEntryIterator iterator() {
            return new LongEntryIterator() {
                int index = 1;
                int readIndex = -1;

                public boolean hasNext() {
                    while (index <= alloc && removed[index]) {
                        index++;
                    }
                    return index <= alloc;
                }

                public long getEntryKey() {
                    return keys[readIndex];
                }

                public long getEntryValue() {
                    return values[readIndex];
                }

                public void next() {
                    if (!hasNext()) {
                        throw new IllegalStateException();
                    }
                    readIndex = index;
                    index++;
                }
            };
        }

        public String toString() {
            LongEntryIterator iterator = iterator();
            StringBuilder builder = new StringBuilder("{");
            while (iterator.hasNext()) {
                iterator.next();
                builder.append(iterator.getEntryKey()).append("->").append(iterator.getEntryValue()).append(',');
            }
            if (builder.charAt(builder.length() - 1) == ',') {
                builder.setLength(builder.length() - 1);
            }
            builder.append('}');
            return builder.toString();
        }

    }

    static class SequenceUtils {
        public static boolean equal(long[] a, int al, int ar, long[] b, int bl, int br) {
            if ((ar - al) != (br - bl)) {
                return false;
            }
            for (int i = al, j = bl; i <= ar; i++, j++) {
                if (a[i] != b[j]) {
                    return false;
                }
            }
            return true;
        }

    }

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

        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 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 LongModular implements ILongModular {
        final long m;

        public LongModular(long m) {
            this.m = m;
        }

        public long mul(long a, long b) {
            return b == 0 ? 0 : ((mul(a, b >> 1) << 1) % m + a * (b & 1)) % m;
        }

    }

    static class LongModularDanger implements ILongModular {
        final long m;

        public LongModularDanger(long m) {
            this.m = m;
        }

        public long mul(long a, long b) {
            return DigitUtils.mulMod(a, b, m);
        }

    }

    static class LongList implements Cloneable {
        private int size;
        private int cap;
        private long[] data;
        private static final long[] EMPTY = new long[0];

        public LongList(int cap) {
            this.cap = cap;
            if (cap == 0) {
                data = EMPTY;
            } else {
                data = new long[cap];
            }
        }

        public LongList(LongList list) {
            this.size = list.size;
            this.cap = list.cap;
            this.data = Arrays.copyOf(list.data, size);
        }

        public LongList() {
            this(0);
        }

        public void ensureSpace(int req) {
            if (req > cap) {
                while (cap < req) {
                    cap = Math.max(cap + 10, 2 * cap);
                }
                data = Arrays.copyOf(data, cap);
            }
        }

        private void checkRange(int i) {
            if (i < 0 || i >= size) {
                throw new ArrayIndexOutOfBoundsException();
            }
        }

        public long get(int i) {
            checkRange(i);
            return data[i];
        }

        public void add(long x) {
            ensureSpace(size + 1);
            data[size++] = x;
        }

        public void addAll(long[] x, int offset, int len) {
            ensureSpace(size + len);
            System.arraycopy(x, offset, data, size, len);
            size += len;
        }

        public void addAll(LongList list) {
            addAll(list.data, 0, list.size);
        }

        public int size() {
            return size;
        }

        public long[] toArray() {
            return Arrays.copyOf(data, size);
        }

        public void clear() {
            size = 0;
        }

        public String toString() {
            return Arrays.toString(toArray());
        }

        public boolean equals(Object obj) {
            if (!(obj instanceof LongList)) {
                return false;
            }
            LongList other = (LongList) obj;
            return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1);
        }

        public int hashCode() {
            int h = 1;
            for (int i = 0; i < size; i++) {
                h = h * 31 + Long.hashCode(data[i]);
            }
            return h;
        }

        public LongList clone() {
            LongList ans = new LongList();
            ans.addAll(this);
            return ans;
        }

    }

    static interface LongEntryIterator {
        boolean hasNext();

        void next();

        long getEntryKey();

        long getEntryValue();

    }

    static interface ILongModular {
        long mul(long a, long b);

        static ILongModular getInstance(long mod) {
            //return new LongModularDanger(mod);
            return mod <= (1L << 54) ? new LongModularDanger(mod) : new LongModular(mod);
        }

    }
}


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

public class E{
    class UnionFind{
        int[] p, size;
        int comps;
        int max;
        UnionFind(int n){
            p = new int[n];
            size = new int[n];
            reset();
        }
        UnionFind(UnionFind old){
            p = old.p.clone();
            size = old.size.clone();
            comps=old.comps;
            max=old.max;
        }
        void reset(){
            for(int i=0; i<p.length; i++){
                p[i]=i;
                size[i]=1;
            }
            comps = p.length;
            max=1;
        }
        int find(int x){
            if(x!=p[x]) p[x]=find(p[x]);
            return p[x];
        }
        void union(int x, int y){
            x = find(x);
            y = find(y);
            if(x!=y)
                if(size[x]>size[y]){
                    p[y]=x;
                    size[x]+=size[y];
                    max=Math.max(max,size[x]);
                }else{
                    p[x]=y;
                    size[y]+=size[x];
                    max=Math.max(max,size[y]);
                }
            comps--;
        }
    }
    static java.io.PrintStream out=System.out;
    int solve(int n, int k, char[][] map){
        UnionFind uf=new UnionFind(n*n);
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(i>0 && map[i][j]=='.' && map[i-1][j]=='.')
                    uf.union(i*n+j,(i-1)*n+j);
                if(j>0 && map[i][j]=='.' && map[i][j-1]=='.')
                    uf.union(i*n+j,i*n+j-1);
            }
        }
        int max=0;
        for(int i=0; i<=n-k; i++)
            for(int j=0; j<=n-k; j++){
                UnionFind bak=new UnionFind(uf);
                for(int x=i; x<i+k; x++)
                    for(int y=j; y<j+k; y++) if(map[x][u]=='X'){
                        if((x==i     && x-1>=0 && map[x-1][y]=='.') || x>i)     bak.union(x*n+y,(x-1)*n+y);
                        if((y==j     && y-1>=0 && map[x][y-1]=='.') || y>j)     bak.union(x*n+y,x*n+y-1);
                        if((x==i+k-1 && x+1<n  && map[x+1][y]=='.') || x<i+k-1) bak.union(x*n+y,(x+1)*n+y);
                        if((y==j+k-1 && y+1<n  && map[x][y+1]=='.') || y<j+k-1) bak.union(x*n+y,x*n+y+1);
                    }
                max=Math.max(max,bak.max);
            }
        return max;
    }
    public static void main(String[] argin) {
        E inst = new E();
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt()){
            int n = in.nextInt(), k=in.nextInt();
            char[][] map = new char[n][];
            for(int i=0; i<n; i++)
                map[i]=in.next().toCharArray();
            out.println(inst.solve(n,k,map));
        }
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class CF303D {

    static long modPow(long x, long pow, long mod) {
        long r = 1;
        while (pow > 0) {
            if (pow % 2 == 1) {
                r = r * x % mod;
            }
            pow /= 2;
            x = x * x % mod;
        }
        return r;
    }

    public static void solve(Input in, PrintWriter out) throws IOException {
        int n = in.nextInt() + 1;
        int x = in.nextInt() - 1;
        for (int d = 2; d * d <= n; ++d) {
            if (n % d == 0) {
                out.println(-1);
                return;
            }
        }
        ArrayList<Integer> pDivs = new ArrayList<Integer>();
        int m = n - 1;
        for (int d = 2; d * d <= m; ++d) {
            if (m % d == 0) {
                pDivs.add(d);
                while (m % d == 0) {
                    m /= d;
                }
            }
        }
        if (m > 1) {
            pDivs.add(m);
        }
        int b;
        if (n == 2) {
            b = 1;
        } else {
            loop: for (b = 2; ; ++b) {
                for (int p : pDivs) {
                    if (modPow(b, (n - 1) / p, n) == 1) {
                        continue loop;
                    }
                }
                break;
            }
        }
        boolean[] coprime = new boolean[n - 1];
        Arrays.fill(coprime, true);
        for (int p : pDivs) {
            for (int i = 0; i < n - 1; i += p) {
                coprime[i] = false;
            }
        }
        long ans = -1;
        long cur = 1;
        for (int i = 0; i < (n == 2 ? 2 : n - 1); ++i) {
            if (coprime[i]) {
                if (cur <= x) {
                    ans = Math.max(ans, cur + n * ((x - cur) / n));
                }
            }
            cur = cur * b % n;
        }
        out.println(ans);
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

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

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

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