import java.math.*;
import java.awt.geom.Line2D;
import java.io.*;
import java.lang.*;
import java.util.*;

public class A implements Runnable {
    public void run() {
        int n = nextInt();
        int m = nextInt();

        char[][] f = new char[n][m];
        for (int i = 0; i < n; ++i) {
            f[i] = nextWord().toCharArray();
        }

        int[][] near = new int[n][m];
        for (int i = 0; i < n; ++i) {
            Arrays.fill(near[i], Integer.MAX_VALUE/3);
            for (int j = 0; j < m; ++j) {
                if (f[i][j] == '1') {
                    near[i][j] = 0;
                    int add = 1;
                    while (f[i][(j+add)%m] != '1' && near[i][(j+add)%m] > add) {
                        near[i][(j+add)%m] = add;
                        ++add;
                    }
                    add = 1;
                    while (f[i][(j-add+m)%m] != '1' && near[i][(j-add+m)%m] > add) {
                        near[i][(j-add+m)%m] = add;
                        ++add;
                    }
                }
            }
        }

        long minAns = Long.MAX_VALUE;
        for (int j = 0; j < m; ++j) {
            long curVal = 0;
            for (int i = 0; i < n; ++i) {
                curVal += near[i][j];
            }

            if (curVal < minAns && curVal < Integer.MAX_VALUE/3) {
                minAns = curVal;
            }
        }
        if (minAns == Long.MAX_VALUE) {
            out.println(-1);
        }
        else {
            out.println(minAns);
        }
        out.flush();
    }

    private static BufferedReader br = null;
    private static StringTokenizer stk = null;
    private static PrintWriter out = null;

    public static void main(String[] args) {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        (new A()).run();
    }

    public void loadLine() {
        try {
            stk = new StringTokenizer(br.readLine());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String nextLine() {
        try {
            return br.readLine();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int nextInt() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Integer.parseInt(stk.nextToken());
    }

    public long nextLong() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Long.parseLong(stk.nextToken());
    }

    public double nextDouble() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Double.parseDouble(stk.nextToken());
    }

    public String nextWord() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return (stk.nextToken());
    }
}


import java.math.*;
import java.awt.geom.Line2D;
import java.io.*;
import java.lang.*;
import java.util.*;

public class A implements Runnable {
    public void run() {
        int n = nextInt();
        int m = nextInt();

        char[][] f = new char[n][m];
        for (int i = 0; i < n; ++i) {
            f[i] = nextWord().toCharArray();
        }

        int[][] near = new int[n][m];
        for (int i = 0; i < n; ++i) {
            Arrays.fill(near[i], Integer.MAX_VALUE/3);
            for (int j = 0; j < m; ++j) {
                if (f[i][j] == '1') {
                    near[i][j] = 0;
                    int add = 1;
                    while (f[i][(j+add)%m] != 1 && near[i][(j+add)%m] > add) {
                        near[i][(j+add)%m] = add;
                        ++add;
                    }
                    add = 1;
                    while (f[i][(j-add+m)%m] != 1 && near[i][(j-add+m)%m] > add) {
                        near[i][(j-add+m)%m] = add;
                        ++add;
                    }
                }
            }
        }

        long minAns = Long.MAX_VALUE;
        for (int j = 0; j < m; ++j) {
            long curVal = 0;
            for (int i = 0; i < n; ++i) {
                curVal += near[i][j];
            }

            if (curVal < minAns && curVal < Integer.MAX_VALUE/3) {
                minAns = curVal;
            }
        }
        if (minAns == Long.MAX_VALUE) {
            out.println(-1);
        }
        else {
            out.println(minAns);
        }
        out.flush();
    }

    private static BufferedReader br = null;
    private static StringTokenizer stk = null;
    private static PrintWriter out = null;

    public static void main(String[] args) {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        (new A()).run();
    }

    public void loadLine() {
        try {
            stk = new StringTokenizer(br.readLine());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String nextLine() {
        try {
            return br.readLine();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int nextInt() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Integer.parseInt(stk.nextToken());
    }

    public long nextLong() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Long.parseLong(stk.nextToken());
    }

    public double nextDouble() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return Double.parseDouble(stk.nextToken());
    }

    public String nextWord() {
        while (stk==null || !stk.hasMoreElements()) loadLine();
        return (stk.nextToken());
    }
}


import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class A229 {
    int colCount,rowCount;
    char table[][];
    int minShift[][];
    void readData(){
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        rowCount = scanner.nextInt();
        colCount = scanner.nextInt();
        table = new char[rowCount][colCount];
        minShift = new int[rowCount][colCount];
        for(int row = 0 ; row < rowCount ; ++row){
            Arrays.fill(minShift[row], Integer.MAX_VALUE/2);
            table[row] = scanner.next().toCharArray();
        }
        scanner.close();
    }
    void solve(){
        for(int row = 0 ; row < rowCount ; ++row){
            int current = Integer.MAX_VALUE / 2;
            for(int col = 0 ; col < colCount ; ++col){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            if ( current >= Integer.MAX_VALUE / 2 ){
                System.out.println(-1);
                return;
            }
            for(int col = 0 ; col < colCount ; ++col){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            current = Integer.MAX_VALUE / 2;
            for(int col = colCount - 1 ; col >= 0 ; --col ){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            for(int col = colCount - 1 ; col >= 0 ; --col ){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;

                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
        }
        int answer = Integer.MAX_VALUE;
        for (int col = 0; col < colCount; col++) {
            int current = 0;
            for (int row = 0; row < rowCount; row++)
                current += minShift[row][col];
            answer = Math.min(answer, current);
        }
        System.out.println(answer);
    }
    public void run(){

        readData();
//      for(int row = 0 ; row < rowCount ; ++row){
//          for(int col = 0 ; col < colCount ; ++col){
//              System.out.print(minShift[row][col]+ " ");
//          }
//          System.out.println();
//      }
        solve();
    }
    public static void main(String[] args) {
        new A229().run();
    }
}


import java.util.Arrays;

public class A229 {
    int colCount,rowCount;
    char table[][];
    int minShift[][];
    void readData(){
        InputReader reader = new InputReader(System.in);
        rowCount = reader.readInt();
        colCount = reader.readInt();
        table = new char[rowCount][colCount];
        minShift = new int[rowCount][colCount];
        for(int row = 0 ; row < rowCount ; ++row){
            Arrays.fill(minShift[row], Integer.MAX_VALUE/2);
            for(int col = 0 ; col < colCount ; ++col){
                table[row][col] = reader.readCharacter();
            }
        }

    }
    void solve(){
        OutputWriter writer = new OutputWriter(System.out);
        for(int row = 0 ; row < rowCount ; ++row){
            int current = Integer.MAX_VALUE / 2;
            for(int col = 0 ; col < colCount ; ++col){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            if ( current >= Integer.MAX_VALUE / 2 ){
                writer.printLine(-1);
                return;
            }
            for(int col = 0 ; col < colCount ; ++col){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            current = Integer.MAX_VALUE / 2;
            for(int col = colCount - 1 ; col >= 0 ; --col ){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;
                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
            for(int col = colCount - 1 ; col >= 0 ; --col ){
                ++current;
                if ( table[row][col] == '1' ){
                    current = 0;

                }
                minShift[row][col] = Math.min(minShift[row][col], current);
            }
        }
//      for(int row = 0 ; row < rowCount ; ++row){
//          for(int col = 0 ; col < colCount ; ++col){
//              System.out.print(minShift[row][col]+ " ");
//          }
//          System.out.println();
//      }
        int answer = Integer.MAX_VALUE;
        for (int col = 0; col < colCount; col++) {
            int current = 0;
            for (int row = 0; row < rowCount; row++)
                current += minShift[row][col];
            answer = Math.min(answer, current);
        }
        System.out.println(answer);
        writer.printLine(answer);
    }
    public void run(){

        readData();
//      for(int row = 0 ; row < rowCount ; ++row){
//          for(int col = 0 ; col < colCount ; ++col){
//              System.out.print(minShift[row][col]+ " ");
//          }
//          System.out.println();
//      }
        solve();
    }
    public static void main(String[] args) {
        new A229().run();
    }
}
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

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

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

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

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

    public char readCharacter() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        return (char) c;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.Writer;

class OutputWriter {
    private final PrintWriter writer;

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

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

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

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

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


#include <bits/stdc++.h>
using namespace std;

string s, ss;
int n;
vector <string> v;
map <string , int> mp;
string ar[150];
vector<pair<int, string>> str;
int a[150];
vector<string> vs;

int main() {
    cin >> s ; cin >> n;
    for(int i=0; i<=n; i++){
        getline(cin, ss);
        ar[i] = ss;
    }

    for(int i=1; i<=n; i++){
        stringstream st(ar[i]);
        string word;
        while(getline(st, word, ' ')) {
            v.push_back(word);
        }
        if(v[1] == "likes"){
            v[2].erase(v[2].size()-2, 2);
//            cout<< "hrer " << v[2] <<endl;
            mp[v[0]] += 5;
            mp[v[2]] += 5;
        }
        else {
            v[3].erase(v[3].size()-2, 2);
//             cout<< "hrer " << v[3] <<endl;
            if(v[1] == "posted"){
                    mp[v[0]] += 15;
                    mp[v[3]] += 15;
            }
            else {
                    mp[v[0]] += 10;
                    mp[v[3]] += 10;
            }
        }
        v.clear();
    }
    for(auto it: mp){
//        cout << it.second << it.first << endl;
        if(it.first == s)continue;
        str.push_back({it.second, it.first});
    }
    sort(str.rbegin(), str.rend());

    for(int i=0; i<str.size(); i++){
        if(!i){
            if(str[i].first == str[i+1].first)a[i] = 1;
        }
        else if(str[i].first == str[i-1].first) a[i] = 1;

        vs.push_back(str[i].second);
    }

//    printf("%d\n", vs.size());

    for(int i=0, j=0; i<vs.size(); i++){
//         printf("f %d\n", a[i]);
        if(!a[i]) continue;
        int cnt= 0;
        for(j=i; j<vs.size(); j++){
            if(!a[j])break;
            cnt++;
        }
        sort(vs.begin() + i, vs.begin() + cnt);
        i += cnt-1;
//     printf("s %d %d\n", i, cnt);
    }
    for(int i=0; i<vs.size(); i++){
        printf("%s\n", vs[i].c_str());
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

char me[12];
char S[102];
map<string, int> score;
int N, M;
string s;

string getX()
{
	int i;
	string ret = "";
	for(i=0; i<(int)s.size() && s[i] != ' '; i++)
		ret += s[i];
	s = "X" + s.substr(i);
	return ret;
}

string getY()
{
	int i;
	bool f = 0;
	string ret = "", rest;
	for(i=(int)s.size()-1; i>=0; i--)
	{
		if(f && s[i] == ' ') break;
		if(f) ret += s[i];
		else rest += s[i];
		if(s[i] == '\'') f = true;
	}
	reverse(ret.begin(), ret.end());
	reverse(rest.begin(), rest.end());
	s = s.substr(0, i+1) + "Y" + rest;
	return ret;
}

int getScore()
{
	if(s == "X posted on Y's wall") return 15;
	if(s == "X commented on Y's post") return 10;
	if(s == "X likes Y's post") return 5;
	return 0;
}

int main()
{
	vector<pair<int, string> > ret;
	scanf("%s", me);
	scanf("%d", &N);
	gets(S);
	for(int i=0; i<N; i++)
	{
		gets(S);
		s = S;
		string X = getX();
		string Y = getY();
		int points = getScore();
		if(X == me || Y == me) points = 0;
		score[X] -= points;
		score[Y] -= points;
	}
	for(map<string, int> :: iterator it = score.begin(); it!=score.end(); it++)
		ret.push_back(make_pair(it->second, it->first));
	sort(ret.begin(), ret.end());
	for(int i=0; i<(int)ret.size(); i++)
	{
		if(ret[i].second == string(me)) continue;
		printf("%s\n", ret[i].second.c_str());
	}
}


#include<bits/stdc++.h>
using namespace std;

char me[12];
char S[102];
map<string, int> score;
int N, M;
string s;

string getX()
{
	int i;
	string ret = "";
	for(i=0; i<(int)s.size() && s[i] != ' '; i++)
		ret += s[i];
	s = "X" + s.substr(i);
	return ret;
}

string getY()
{
	int i;
	bool f = 0;
	string ret = "", rest;
	for(i=(int)s.size()-1; i>=0; i--)
	{
		if(f && s[i] == ' ') break;
		if(f) ret += s[i];
		else rest += s[i];
		if(s[i] == '\'') f = true;
	}
	reverse(ret.begin(), ret.end());
	reverse(rest.begin(), rest.end());
	s = s.substr(0, i+1) + "Y" + rest;
	return ret;
}

int getScore()
{
	if(s == "X posted on Y's wall") return 15;
	if(s == "X commented on Y's post") return 10;
	if(s == "X likes Y's post") return 5;
	return 0;
}

int main()
{
	vector<pair<int, string> > ret;
	scanf("%s", me);
	scanf("%d", &N);
	gets(S);
	for(int i=0; i<N; i++)
	{
		gets(S);
		s = S;
		string X = getX();
		string Y = getY();
		int points = getScore();
		if(X != me && Y != me) points = 0;
		score[X] -= points;
		score[Y] -= points;
	}
	for(map<string, int> :: iterator it = score.begin(); it!=score.end(); it++)
		ret.push_back(make_pair(it->second, it->first));
	sort(ret.begin(), ret.end());
	for(int i=0; i<(int)ret.size(); i++)
	{
		if(ret[i].second == string(me)) continue;
		printf("%s\n", ret[i].second.c_str());
	}
}


#include<bits/stdc++.h>
using namespace std;

char me[12];
char S[102];
map<string, int> score;
int N, M;
string s;

string getX()
{
	int i;
	string ret = "";
	for(i=0; i<(int)s.size() && s[i] != ' '; i++)
		ret += s[i];
	s = "X" + s.substr(i);
	return ret;
}

string getY()
{
	int i;
	bool f = 0;
	string ret = "", rest;
	for(i=(int)s.size()-1; i>=0; i--)
	{
		if(f && s[i] == ' ') break;
		if(f) ret += s[i];
		else rest += s[i];
		if(s[i] == '\'') f = true;
	}
	reverse(ret.begin(), ret.end());
	reverse(rest.begin(), rest.end());
	s = s.substr(0, i+1) + "Y" + rest;
	return ret;
}

int getScore()
{
	if(s == "X posted on Y's wall") return 15;
	if(s == "X commented on Y's post") return 10;
	if(s == "X likes Y's post") return 5;
	return 0;
}

int main()
{
	vector<pair<int, string> > ret;
	scanf("%s", me);
	scanf("%d", &N);
	gets(S);
	for(int i=0; i<N; i++)
	{
		gets(S);
		s = S;
		string X = getX();
		string Y = getY();
		int points = getScore();
		if(X == me || Y == me)
		{
			score[X] -= points;
			score[Y] -= points;
		}
	}
	for(map<string, int> :: iterator it = score.begin(); it!=score.end(); it++)
		ret.push_back(make_pair(it->second, it->first));
	sort(ret.begin(), ret.end());
	for(int i=0; i<(int)ret.size(); i++)
	{
		if(ret[i].second == string(me)) continue;
		printf("%s\n", ret[i].second.c_str());
	}
}


import java.util.*;
import java.io.*;
public class Main {
    static class Scan {
        private byte[] buf=new byte[1024];
        private int index;
        private InputStream in;
        private int total;
        public Scan()
        {
            in=System.in;
        }
        public int scan()throws IOException
        {
            if(total<0)
            throw new InputMismatchException();
            if(index>=total)
            {
                index=0;
                total=in.read(buf);
                if(total<=0)
                return -1;
            }
            return buf[index++];
        }
        public int scanInt()throws IOException
        {
            int integer=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    integer*=10;
                    integer+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            return neg*integer;
        }
        public double scanDouble()throws IOException
        {
            double doub=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n)&&n!='.')
            {
                if(n>='0'&&n<='9')
                {
                    doub*=10;
                    doub+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            if(n=='.')
            {
                n=scan();
                double temp=1;
                while(!isWhiteSpace(n))
                {
                    if(n>='0'&&n<='9')
                    {
                        temp/=10;
                        doub+=(n-'0')*temp;
                        n=scan();
                    }
                    else throw new InputMismatchException();
                }
            }
            return doub*neg;
        }
        public String scanString()throws IOException
        {
            StringBuilder sb=new StringBuilder();
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            while(!isWhiteSpace(n))
            {
                sb.append((char)n);
                n=scan();
            }
            return sb.toString();
        }
        private boolean isWhiteSpace(int n)
        {
            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
            return true;
            return false;
        }
    }

    public static void sort(int arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(int arr[],int l1,int r1,int l2,int r2) {
        int tmp[]=new int[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void sort(long arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(long arr[],int l1,int r1,int l2,int r2) {
        long tmp[]=new long[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void main(String args[]) throws IOException {
        Scan input=new Scan();
        StringBuilder ans=new StringBuilder("");
        int a=input.scanInt();
        int b=input.scanInt();
        Set<Integer> hashset=new HashSet<>();
        for(int i=1;i<=Math.sqrt(a);i++) {
            if(a%i==0) {
                if(a/i==i) {
                    hashset.add(i);
                }
                else {
                    hashset.add(i);
                    hashset.add(a/i);
                }
            }
        }
        int cnt=0;
        for(int i=1;i<=Math.sqrt(b);i++) {
            if(b%i==0) {
                if(b/i==i) {
                    if(hashset.contains(i)) {
                        cnt++;
                    }
                }
                else {
                    if(hashset.contains(i)) {
                        cnt++;
                    }
                    if(hashset.contains(b/i)) {
                        cnt++;
                    }
                }
            }
        }
        int arr[]=new int[cnt];
        cnt=0;
        for(int i=1;i<=Math.sqrt(b);i++) {
            if(b%i==0) {
                if(b/i==i) {
                    if(hashset.contains(i)) {
                        arr[cnt]=i;
                        cnt++;
                    }
                }
                else {
                    if(hashset.contains(i)) {
                        arr[cnt]=i;
                        cnt++;
                    }
                    if(hashset.contains(b/i)) {
                        arr[cnt]=b/i;
                        cnt++;
                    }
                }
            }
        }
        sort(arr,0,arr.length-1);
        int test=input.scanInt();
        for(int tt=1;tt<=test;tt++) {
            int l=input.scanInt();
            int r=input.scanInt();
            int indx=search(arr,r);
            if(indx==-1) {
                ans.append(-1);
                ans.append("\n");
                continue;
            }
            if(arr[indx]<l) {
                ans.append(-1);
                ans.append("\n");
            }
            else {
                ans.append(arr[indx]);
                ans.append("\n");
            }
        }
        System.out.println(ans);
    }
    public static int search(int arr[],int val) {
        int ans=-1,l=0,r=arr.length-1;
        while(l<=r) {
            int mid=(l+r)/2;
            if(arr[mid]<=val) {
                ans=mid;
                l=mid+1;
            }
            else {
                r=mid-1;
            }
        }
        return ans;
    }
}


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

public class GCD
{
	public static void main(String args[])throws Exception
	{
		BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
		String s[]=bu.readLine().split(" ");
		int a=Integer.parseInt(s[0]),b=Integer.parseInt(s[1]),i;
		ArrayList<Integer> g=new ArrayList<>();
		if(b>a) a=a^b^(b=a);
		while(b!=0)
		{
			int temp=b;
			b=a%b;
			a=temp;
		}
		for(i=1;i*i<=a;i++)
		if(a%i==0)
		{
			g.add(i);
			if(a/i!=i) g.add(a/i);
		}

		int n=Integer.parseInt(bu.readLine());
		StringBuilder sb=new StringBuilder();
		while(n-->0)
		{
			s=bu.readLine().split(" ");
			int l=Integer.parseInt(s[0]),r=Integer.parseInt(s[1]),ans=-1;
			for(i=0;i<g.size();i++)
			{
				int x=g.get(i);
				if(x>=l && x<=r) ans=x>ans?x:ans;
			}
			sb.append(ans+"\n");
		}
		System.out.print(sb);
	}
}


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

public class GCD
{
	public static void main(String args[])throws Exception
	{
		BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
		String s[]=bu.readLine().split(" ");
		int a=Integer.parseInt(s[0]),b=Integer.parseInt(s[1]),i;
		ArrayList<Integer> g=new ArrayList<>();
		if(b>a) a=a^b^(b=a);
		while(b!=0)
		{
			int temp=b;
			b=a%b;
			a=temp;
		}
		g.add(1);
		for(i=2;i<=a/2;i++)
		if(a%i==0) g.add(i);
		g.add(a);

		int n=Integer.parseInt(bu.readLine());
		StringBuilder sb=new StringBuilder();
		while(n-->0)
		{
			s=bu.readLine().split(" ");
			int l=Integer.parseInt(s[0]),r=Integer.parseInt(s[1]),ans=-1;
			for(i=0;i<g.size();i++)
			{
				int x=g.get(i);
				if(x>r) break;
				if(x>=l && x<=r) ans=x;
			}
			sb.append(ans+"\n");
		}
		System.out.print(sb);
	}
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

public class Solution {

    public static void main(String[] args) {
        try (PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) {

            _Scanner sc = new _Scanner(System.in);

            int a = sc.nextInt();
            int b = sc.nextInt();
            int n = sc.nextInt();

            int g = gcd(a, b);

            List<Integer> divisors = new ArrayList<>();
            for (int i = 1; i * i <= g; i++) {
                if (g % i == 0) {
                    divisors.add(i);
                    divisors.add(g / i);
                }
            }

            Collections.sort(divisors);

            for (int i = 0; i < n; i++) {
                int low = sc.nextInt();
                int high = sc.nextInt();

                int x = -1;
                int dn = divisors.size();
                for (int step = dn; step > 0; step /= 2) {
                    while (x + step < dn && divisors.get(x + step) <= high) x += step;
                }

                if (x >= 0 && divisors.get(x) >= low) {
                    out.println(divisors.get(x));
                } else {
                    out.println(-1);
                }
            }
        }
    }

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

    static class _Scanner {
        InputStream is;
        _Scanner(InputStream is) {
            this.is = is;
        }
        byte[] bb = new byte[1 << 15];
        int k, l;
        byte getc() {
            try {
                if (k >= l) {
                    k = 0;
                    l = is.read(bb);
                    if (l < 0) return -1;
                }
                return bb[k++];
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        byte skip() {
            byte b;
            while ((b = getc()) <= 32)
                ;
            return b;
        }

        int nextInt() {
            int n = 0;
            int sig = 1;
            for (byte b = skip(); b > 32; b = getc()) {
                if (b == '-') {
                    sig = -1;
                } else {
                    n = n * 10 + b - '0';
                }
            }
            return sig * n;
        }

        long nextLong() {
            long n = 0;
            long sig = 1;
            for (byte b = skip(); b > 32; b = getc()) {
                if (b == '-') {
                    sig = -1;
                } else {
                    n = n * 10 + b - '0';
                }
            }
            return sig * n;
        }

        public String next() {
            StringBuilder sb = new StringBuilder();
            for (int b = skip(); b > 32; b = getc()) {
                sb.append(((char) b));
            }
            return sb.toString();
        }
    }

    private static void shuffle(int[] ar) {
        Random rnd = new Random();
        for (int i = 0; i < ar.length; i++) {
            int j = i + rnd.nextInt(ar.length - i);
            swap(ar, i, j);
        }
    }

    private static void shuffle(Object[] ar) {
        Random rnd = new Random();
        for (int i = 0; i < ar.length; i++) {
            int j = i + rnd.nextInt(ar.length - i);
            swap(ar, i, j);
        }
    }

    private static void swap(int[] ar, int i, int j) {
        int t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }

    private static void swap(Object[] ar, int i, int j) {
        Object t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }

    private static class MyScanner {

        private final BufferedReader reader;
        private StringTokenizer tokenizer;

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

        public int nextInt() {
            reload();
            if (tokenizer.hasMoreTokens()) {
                return Integer.parseInt(tokenizer.nextToken());
            }
            throw new RuntimeException("eof");
        }

        private void reload() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(readline());
            }
        }

        private String readline() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public String next() {
            reload();
            return tokenizer.nextToken();
        }
    }

}


// Imports
import java.util.*;
import java.io.*;

public class C75 {

    static SortedSet<Long> factors;
    public static void loadPrimeFactorization(long n) {
        factors = new TreeSet<>();

        for(long i = 1; i <= Math.sqrt(n); i++) {
            if(n%i == 0) {
                factors.add(i);
                factors.add(n/i);
            }
        }
    }

    static long gcd(long a, long b) {
        if(a < 0 || b < 0) {
            return -1;
        }

        // Everything divides 0
        while (a != b) {

            if(a == 0) {
                return b;
            }
            if(b == 0) {
                return a;
            }

            if (a > b) {
                long floor = a/b;
                a = a - (b*floor);
            }
            else {
                long floor = b/a;
                b = b - (a*floor);
            }

        }
        return a;
    }

    /**
     * @param args the command line arguments
     * @throws IOException, FileNotFoundException
     */
    public static void main(String[] args) throws IOException, FileNotFoundException {

        // TODO UNCOMMENT WHEN ALGORITHM CORRECT
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

        // TODO code application logic here
        StringTokenizer st = new StringTokenizer(f.readLine());
        long A = Integer.parseInt(st.nextToken());
        long B = Integer.parseInt(st.nextToken());
        long factor = gcd(A, B);

        loadPrimeFactorization(factor);

        Long[] arr = factors.toArray(new Long[factors.size()]);
        System.out.println(Arrays.toString(arr));

        int N = Integer.parseInt(f.readLine());
        for(int i = 0; i < N; i++) {
            StringTokenizer query = new StringTokenizer(f.readLine());
            long q1 = Integer.parseInt(query.nextToken());
            long q2 = Integer.parseInt(query.nextToken());

            int curr = Arrays.binarySearch(arr, q2);
            // System.out.println(curr);
            if(curr > 0) {
                System.out.println(arr[curr]);
            }
            else {
                if(arr[-1*curr - 2] < q1) {
                    System.out.println(-1);
                }
                else {
                    System.out.println(arr[-1*curr - 2]);
                }
            }
        }
    }

}


// Imports
import java.util.*;
import java.io.*;

public class C75 {

    static SortedSet<Long> factors;
    public static void loadPrimeFactorization(long n) {
        factors = new TreeSet<>();

        for(long i = 1; i <= Math.sqrt(n); i++) {
            if(n%i == 0) {
                factors.add(i);
                factors.add(n/i);
            }
        }
    }

    static long gcd(long a, long b) {
        if(a < 0 || b < 0) {
            return -1;
        }

        // Everything divides 0
        while (a != b) {

            if(a == 0) {
                return b;
            }
            if(b == 0) {
                return a;
            }

            if (a > b) {
                long floor = a/b;
                a = a - (b*floor);
            }
            else {
                long floor = b/a;
                b = b - (a*floor);
            }

        }
        return a;
    }

    /**
     * @param args the command line arguments
     * @throws IOException, FileNotFoundException
     */
    public static void main(String[] args) throws IOException, FileNotFoundException {

        // TODO UNCOMMENT WHEN ALGORITHM CORRECT
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

        // TODO code application logic here
        StringTokenizer st = new StringTokenizer(f.readLine());
        long A = Integer.parseInt(st.nextToken());
        long B = Integer.parseInt(st.nextToken());
        long factor = gcd(A, B);

        loadPrimeFactorization(factor);

        Long[] arr = factors.toArray(new Long[factors.size()]);
        // System.out.println(Arrays.toString(arr));

        int N = Integer.parseInt(f.readLine());
        for(int i = 0; i < N; i++) {
            StringTokenizer query = new StringTokenizer(f.readLine());
            long q1 = Integer.parseInt(query.nextToken());
            long q2 = Integer.parseInt(query.nextToken());

            int curr = Arrays.binarySearch(arr, q2);
            // System.out.println(curr);
            if(curr > 0) {
                System.out.println(arr[curr]);
            }
            else {
                if(arr[-1*curr - 2] < q1) {
                    System.out.println(-1);
                }
                else {
                    System.out.println(arr[-1*curr - 2]);
                }
            }
        }
    }

}


// Imports
import java.util.*;
import java.io.*;

public class C75 {

    static SortedSet<Long> factors;
    public static void loadPrimeFactorization(long n) {
        factors = new TreeSet<>();

        for(long i = 1; i <= Math.sqrt(n); i++) {
            if(n%i == 0) {
                factors.add(i);
                factors.add(n/i);
            }
        }
    }

    static long gcd(long a, long b) {
        if(a < 0 || b < 0) {
            return -1;
        }

        // Everything divides 0
        while (a != b) {

            if(a == 0) {
                return b;
            }
            if(b == 0) {
                return a;
            }

            if (a > b) {
                long floor = a/b;
                a = a - (b*floor);
            }
            else {
                long floor = b/a;
                b = b - (a*floor);
            }

        }
        return a;
    }

    /**
     * @param args the command line arguments
     * @throws IOException, FileNotFoundException
     */
    public static void main(String[] args) throws IOException, FileNotFoundException {

        // TODO UNCOMMENT WHEN ALGORITHM CORRECT
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

        // TODO code application logic here
        StringTokenizer st = new StringTokenizer(f.readLine());
        long A = Integer.parseInt(st.nextToken());
        long B = Integer.parseInt(st.nextToken());
        long factor = gcd(A, B);

        loadPrimeFactorization(factor);

        Long[] arr = factors.toArray(new Long[factors.size()]);
        // System.out.println(Arrays.toString(arr));

        int N = Integer.parseInt(f.readLine());
        for(int i = 0; i < N; i++) {
            StringTokenizer query = new StringTokenizer(f.readLine());
            long q1 = Integer.parseInt(query.nextToken());
            long q2 = Integer.parseInt(query.nextToken());

            int curr = Arrays.binarySearch(arr, q2);
            // System.out.println(curr);
            if(curr >= 0) {
                System.out.println(arr[curr]);
            }
            else {
                if(arr[-1*curr - 2] < q1) {
                    System.out.println(-1);
                }
                else {
                    System.out.println(arr[-1*curr - 2]);
                }
            }
        }
    }

}


// Imports
import java.util.*;
import java.io.*;

public class C75 {

    static SortedSet<Long> factors;
    public static void loadPrimeFactorization(long n) {
        factors = new TreeSet<>();

        for(long i = 1; i <= Math.sqrt(n); i++) {
            if(n%i == 0) {
                factors.add(i);
                factors.add(n/i);
            }
        }
    }

    static long gcd(long a, long b) {
        if(a < 0 || b < 0) {
            return -1;
        }

        // Everything divides 0
        while (a != b) {

            if(a == 0) {
                return b;
            }
            if(b == 0) {
                return a;
            }

            if (a > b) {
                long floor = a/b;
                a = a - (b*floor);
            }
            else {
                long floor = b/a;
                b = b - (a*floor);
            }

        }
        return a;
    }

    /**
     * @param args the command line arguments
     * @throws IOException, FileNotFoundException
     */
    public static void main(String[] args) throws IOException, FileNotFoundException {

        // TODO UNCOMMENT WHEN ALGORITHM CORRECT
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

        // TODO code application logic here
        StringTokenizer st = new StringTokenizer(f.readLine());
        long A = Integer.parseInt(st.nextToken());
        long B = Integer.parseInt(st.nextToken());
        long factor = gcd(A, B);

        loadPrimeFactorization(factor);

        Long[] arr = factors.toArray(new Long[factors.size()]);
        // System.out.println(Arrays.toString(arr));

        int N = Integer.parseInt(f.readLine());
        for(int i = 0; i < N; i++) {
            StringTokenizer query = new StringTokenizer(f.readLine());
            long q1 = Integer.parseInt(query.nextToken());
            long q2 = Integer.parseInt(query.nextToken());

            int curr = Arrays.binarySearch(arr, q2);
            // System.out.println(curr);
            if(curr > 0) {
                System.out.println(arr[curr]);
            }
            else {
                if(-1*curr - 2 < 0 || arr[-1*curr - 2] < q1) {
                    System.out.println(-1);
                }
                else {
                    System.out.println(arr[-1*curr - 2]);
                }
            }
        }
    }

}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);
       ai.add(gc);
       for(int i=gc/2;i>1;i--)
           if(gc%i==0) {
               ai.add(i);
           }
             ai.add(1);
        System.out.println(ai);

       while(n-->0) {
           boolean f = false;
           int l = sc.nextInt();
           int h = sc.nextInt();

           if (l > gc)
               System.out.println("-1");

           else if (h == 1)
               System.out.println("1");
           else {
               for (Integer x : ai)
                   if (x >= l && x <= h) {
                       System.out.println(x);
                       f = true;
                       break;
                   }

               if (!f)
                   System.out.println(-1);
           }
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        int ai[]= new int[1000];
       int gc=g(a,b);
       int j=0;
       int count=0;
       for(int i=gc;i>=1;i--)
           if(gc%i==0) {
               ai[j++] = i;
               count++;
           }

       while(n-->0){
           boolean f=false;
           int l=sc.nextInt();
           int h=sc.nextInt();
           for( int i=0;i<=count;i++)
           {
               if(ai[i]>=l&&ai[i]<=h) {
                   System.out.println(ai[i]);
                   f = true;
                   break;
               }
           }
           if(!f)
               System.out.println(-1);

       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        int ai[]= new int[1000];
       int gc=g(a,b);
       ai[0]=gc;
       int j=1;
       int count=0;
       for(int i=gc/2;i>=1;i--)
           if(gc%i==0) {
               ai[j++] = i;
               count++;
           }

       while(n-->0){
           boolean f=false;
           int l=sc.nextInt();
           int h=sc.nextInt();
           if(l==1&& h==1)
               System.out.println(1);
            else {
               for (int i = 0; i <= count; i++) {
                   if (ai[i] >= l && ai[i] <= h) {
                       System.out.println(ai[i]);
                       f = true;
                       break;
                   }
               }
           }

           if(!f)
               System.out.println(-1);

       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);

       for(int i=1;i<=Math.sqrt(gc);i++)
           if(gc%i==0) {
               ai.add(i);
               if(i*i!=Math.sqrt(gc))
               ai.add(gc/i);
           }
             Collections.sort(ai,Collections.reverseOrder());

       while(n-->0) {
           boolean f = false;
           int l = sc.nextInt();
           int h = sc.nextInt();

           if (l > gc)
               System.out.println("-1");

           else if (h == 1)
               System.out.println("1");
           else {
               for (Integer x : ai)
                   if (x >= l && x <= h) {
                       System.out.println(x);
                       f = true;
                       break;
                   }

               if (!f)
                   System.out.println(-1);
           }
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai=new ArrayList<>();
       int gc=g(a,b);
       for(int i=gc;i>=1;i--)
           if(gc%i==0)
               ai.add(i);

       while(n-->0){
           boolean f=false;
           int l=sc.nextInt();
           int h=sc.nextInt();
           for( Integer x:ai)
           {
               if(x>=l&&x<=h) {
                   System.out.println(x);
                   f = true;
                   break;
               }
           }
           if(!f)
               System.out.println(-1);

       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);

       for(int i=1;i<=Math.sqrt(gc);i++)
           if(gc%i==0) {
               ai.add(i);
               if(i*i!=gc)
               ai.add(gc/i);
           }
             Collections.sort(ai,Collections.reverseOrder());
        System.out.println(ai);

       while(n-->0) {
           boolean f = false;
           int l = sc.nextInt();
           int h = sc.nextInt();

           if (l > gc)
               System.out.println("-1");

           else if (h == 1)
               System.out.println("1");
           else {
               for (Integer x : ai)
                   if (x >= l && x <= h) {
                       System.out.println(x);
                       f = true;
                       break;
                   }

               if (!f)
                   System.out.println(-1);
           }
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);
       ai.add(gc);
       for(int i=gc/2;i>1;i--)
           if(gc%i==0) {
               ai.add(i);
           }
             ai.add(1);

       while(n-->0) {
           boolean f = false;
           int l = sc.nextInt();
           int h = sc.nextInt();

           if (l > gc)
               System.out.println("-1");

           else if (h == 1)
               System.out.println("1");
           else {
               for (Integer x : ai)
                   if (x >= l && x <= h) {
                       System.out.println(x);
                       f = true;
                       break;
                   }

               if (!f)
                   System.out.println(-1);
           }
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);

       for(int i=1;i<=Math.sqrt(gc);i++)
           if(gc%i==0) {
               ai.add(i);
               if(i*i!=gc)
               ai.add(gc/i);
           }
             Collections.sort(ai,Collections.reverseOrder());

       while(n-->0) {
           boolean f = false;
           int l = sc.nextInt();
           int h = sc.nextInt();

           if (l > gc)
               System.out.println("-1");

           else if (h == 1)
               System.out.println("1");
           else {
               for (Integer x : ai)
                   if (x >= l && x <= h) {
                       System.out.println(x);
                       f = true;
                       break;
                   }

               if (!f)
                   System.out.println(-1);
           }
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class GCD {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int a,b,n;
       a= sc.nextInt();
       b=sc.nextInt();
       n=sc.nextInt();
        ArrayList<Integer> ai= new ArrayList<>();
       int gc=g(a,b);
       ai.add(gc);
       for(int i=gc/2;i>1;i--)
           if(gc%i==0) {
               ai.add(i);
           }
             ai.add(1);

       while(n-->0){
           boolean f=false;
           int l=sc.nextInt();
           int h=sc.nextInt();

           if(l>gc)
               System.out.println("-1");

          else if(h==1)
               System.out.println("1");
          else
               for(int i=1;i<ai.size();i++)
                   if(ai.get(i)>=l&&ai.get(i)<=h) {
                       System.out.println(ai.get(i));
                       f=true;
                       break;
                   }

           if(!f)
               System.out.println(-1);
       }

    }

    public static int g(int a, int b){
        if(b==0)
            return a;
        return g(b,a%b);
    }
}


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

public class MGCD {
    static class Solver {
        public void solve(MyReader in, PrintWriter out) {

            int a = in.nextInt();
            int b = in.nextInt();

            int min = Math.min(a,b);
            int max=  Math.max(a,b);

            var firstDiv = new HashSet<>();
            NavigableSet<Integer> divs = new TreeSet<>();

            for(int i = 1;i*i<=min;i++){
                if(min%i == 0){
                    firstDiv.add(i);
                    firstDiv.add(min/i);
                }
            }

            for(int i = 1;i*i<=max;i++){
                if(max%i == 0){
                    if(firstDiv.contains(i))divs.add(i);
                    if(firstDiv.contains(max/i))divs.add(max/i);
                }
            }

//            out.println(divs);
            int n = in.nextInt();

            for (int i = 0; i < n; i++) {
                int l = in.nextInt();
                int r = in.nextInt();

                var set = divs.subSet(l,true,r,true);
                if(set.isEmpty()){
                    out.println(-1);
                }
                else{
                    int res = set.pollLast();
                    out.println(res);
                    set.add(res);
                }
            }

        }

    }

    public static void main(String[] args) {
        MyReader mr = new MyReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        new Solver().solve(mr, out);
        out.close();
    }

    //    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}};
//    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}, {-1,-1},{-1,1}, {1,1}, {1,-1}};
    static class MyReader {
        BufferedReader br;
        StringTokenizer st;

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

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception 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 res = "";
            try {
                res = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return res;
        }

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

            return arr;
        }

        Integer[] nextIntegerArray(int n) {
            Integer[] arr = new Integer[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }

            return arr;
        }

        Long[] nextLongArray(int n) {
            Long[] arr = new Long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }

            return arr;
        }

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

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

}


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

public class MGCD {
    static class Solver {
        public void solve(MyReader in, PrintWriter out) {

            int a = in.nextInt();
            int b = in.nextInt();

            int min = Math.min(a,b);
            int max=  Math.max(a,b);

            NavigableSet<Integer> divs = new TreeSet<>();

            for(int i = 1;i*i<=min;i++){
                if(min%i == 0){
                    divs.add(i);
                    divs.add(min/i);
                }
            }

            for(int i = 1;i*i<=max;i++){
                if(max%i == 0){
                    if(!divs.contains(i)){
                        divs.remove(i);
                    }
                    if(!divs.contains(max/i))
                        divs.remove(max/i);
                }
            }

            int n = in.nextInt();

            for (int i = 0; i < n; i++) {
                int l = in.nextInt();
                int r = in.nextInt();

                var set = divs.subSet(l,true,r,true);
                if(set.isEmpty()){
                    out.println(-1);
                }
                else{
                    out.println(set.pollLast());
                }
            }

        }

    }

    public static void main(String[] args) {
        MyReader mr = new MyReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        new Solver().solve(mr, out);
        out.close();
    }

    //    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}};
//    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}, {-1,-1},{-1,1}, {1,1}, {1,-1}};
    static class MyReader {
        BufferedReader br;
        StringTokenizer st;

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

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception 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 res = "";
            try {
                res = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return res;
        }

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

            return arr;
        }

        Integer[] nextIntegerArray(int n) {
            Integer[] arr = new Integer[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }

            return arr;
        }

        Long[] nextLongArray(int n) {
            Long[] arr = new Long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }

            return arr;
        }

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

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

}


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

public class MGCD {
    static class Solver {
        public void solve(MyReader in, PrintWriter out) {

            int a = in.nextInt();
            int b = in.nextInt();

            int min = Math.min(a,b);
            int max=  Math.max(a,b);

            var firstDiv = new HashSet<>();
            NavigableSet<Integer> divs = new TreeSet<>();

            for(int i = 1;i*i<=min;i++){
                if(min%i == 0){
                    firstDiv.add(i);
                    firstDiv.add(min/i);
                }
            }

            for(int i = 1;i*i<=max;i++){
                if(max%i == 0){
                    if(firstDiv.contains(i))divs.add(i);
                    if(firstDiv.contains(max/i))divs.add(max/i);
                }
            }

            int n = in.nextInt();

            for (int i = 0; i < n; i++) {
                int l = in.nextInt();
                int r = in.nextInt();

                var set = divs.subSet(l,true,r,true);
                if(set.isEmpty()){
                    out.println(-1);
                }
                else{
                    out.println(set.pollLast());
                }
            }

        }

    }

    public static void main(String[] args) {
        MyReader mr = new MyReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        new Solver().solve(mr, out);
        out.close();
    }

    //    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}};
//    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}, {-1,-1},{-1,1}, {1,1}, {1,-1}};
    static class MyReader {
        BufferedReader br;
        StringTokenizer st;

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

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception 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 res = "";
            try {
                res = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return res;
        }

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

            return arr;
        }

        Integer[] nextIntegerArray(int n) {
            Integer[] arr = new Integer[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }

            return arr;
        }

        Long[] nextLongArray(int n) {
            Long[] arr = new Long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }

            return arr;
        }

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

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

}


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

public class MGCD {
    static class Solver {
        public void solve(MyReader in, PrintWriter out) {

            int a = in.nextInt();
            int b = in.nextInt();

            int min = Math.min(a,b);
            int max=  Math.max(a,b);

            var firstDiv = new HashSet<>();
            NavigableSet<Integer> divs = new TreeSet<>();

            for(int i = 1;i*i<=min;i++){
                if(min%i == 0){
                    firstDiv.add(i);
                    firstDiv.add(min/i);
                }
            }

            for(int i = 1;i*i<=max;i++){
                if(max%i == 0){
                    if(firstDiv.contains(i))divs.add(i);
                    if(firstDiv.contains(max/i))divs.add(max/i);
                }
            }

            out.println(divs);
            int n = in.nextInt();

            for (int i = 0; i < n; i++) {
                int l = in.nextInt();
                int r = in.nextInt();

                var set = divs.subSet(l,true,r,true);
                if(set.isEmpty()){
                    out.println(-1);
                }
                else{
                    int res = set.pollLast();
                    out.println(res);
                    set.add(res);
                }
            }

        }

    }

    public static void main(String[] args) {
        MyReader mr = new MyReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        new Solver().solve(mr, out);
        out.close();
    }

    //    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}};
//    static int[][] dir = {{0,1}, {1,0},{-1,0}, {0,-1}, {-1,-1},{-1,1}, {1,1}, {1,-1}};
    static class MyReader {
        BufferedReader br;
        StringTokenizer st;

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

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception 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 res = "";
            try {
                res = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return res;
        }

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

            return arr;
        }

        Integer[] nextIntegerArray(int n) {
            Integer[] arr = new Integer[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }

            return arr;
        }

        Long[] nextLongArray(int n) {
            Long[] arr = new Long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }

            return arr;
        }

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

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

}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;

public class Main{
    public static LinkedList div(int r)
    {
         LinkedList<Integer> li=new LinkedList<>();
         int rr=(int)Math.sqrt(r);
         for(int i=1;i<=rr;i++)
         {
             if(r%i==0)
             {
                 li.add(i);
                 li.add(r/i);
             }
         }
         if(rr==li.get(li.size()-1)){
             li.remove(li.size()-1);
         }
         Collections.sort(li);
        return li;
    }

    public static int gcd(int m,int n)
    {
        while(n != 0) {
        int t = m % n;
        m = n;
        n = t;
	}

    return m;
    }
    public static int lowerbound(LinkedList<Integer> l,int length,int value)
    {
          int low = 0;
        int high = length;
        while (low < high) {
            final int mid = (low + high) / 2;
            if (value >= l.get(mid)) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;

    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a,b;
        a=sc.nextInt();
        b=sc.nextInt();

        int hd=gcd(a,b);
        LinkedList<Integer> l=new LinkedList<>();
        l=div(hd);

        int n=sc.nextInt();
        for (int i=0;i<n;i++)
        {
            int low=sc.nextInt();
            int hig=sc.nextInt();
            int inx=lowerbound(l,l.size(),hig);

            if(l.get(inx-1)>=low && inx>0)
            {
               System.out.println(l.get(inx-1));
            }
            else{
                 System.out.println(-1);
            }

        }

    }

}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;

public class Main{
    public static LinkedList div(int r)
    {
         LinkedList<Integer> li=new LinkedList<>();
         int rr=(int)Math.sqrt(r);
         for(int i=1;i<=rr;i++)
         {
             if(r%i==0)
             {
                 li.add(i);
                 li.add(r/i);
             }
         }
         if(rr==li.get(li.size()-1)){
             li.remove(li.size()-1);
         }
         Collections.sort(li);
        return li;
    }

    public static int gcd(int m,int n)
    {
        while(n != 0) {
        int t = m % n;
        m = n;
        n = t;
	}

    return m;
    }
    public static int lowerbound(LinkedList<Integer> l,int length,int value)
    {
         int low = 0;
        int high = length;
        while (low < high) {
            final int mid = (low + high) / 2;
            //checks if the value is less than middle element of the array
            if (value <= l.get(mid)) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return low-1;

    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a,b;
        a=sc.nextInt();
        b=sc.nextInt();

        int hd=gcd(a,b);
        LinkedList<Integer> l=new LinkedList<>();
        l=div(hd);

        int n=sc.nextInt();
        for (int i=0;i<n;i++)
        {
            int low=sc.nextInt();
            int hig=sc.nextInt();
            int inx=lowerbound(l,l.size(),hig);

            if(l.get(inx)>=low && inx>=0)
            {  if( (inx+1)<l.size() && l.get(inx+1)==hig )
            {
                 System.out.println(l.get(inx+1));
            }
            else{
                System.out.println(l.get(inx));}
            }
            else{
                 System.out.println(-1);
            }

        }

    }

}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;

public class Main{
    public static LinkedList div(int r)
    {
         LinkedList<Integer> li=new LinkedList<>();
         int rr=(int)Math.sqrt(r);
         for(int i=1;i<=rr;i++)
         {
             if(r%i==0)
             {
                 li.add(i);
                 li.add(r/i);
             }
         }
         if(rr==li.get(li.size()-1)){
             li.remove(li.size()-1);
         }
         Collections.sort(li);
        return li;
    }

    public static int gcd(int m,int n)
    {
        while(n != 0) {
        int t = m % n;
        m = n;
        n = t;
	}

    return m;
    }
    public static int lowerbound(LinkedList<Integer> l,int length,int value)
    {
         int low = 0;
        int high = length;
        while (low < high) {
            final int mid = (low + high) / 2;
            //checks if the value is less than middle element of the array
            if (value <= l.get(mid)) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return low-1;

    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a,b;
        a=sc.nextInt();
        b=sc.nextInt();

        int hd=gcd(a,b);
        LinkedList<Integer> l=new LinkedList<>();
        l=div(hd);

        int n=sc.nextInt();
        for (int i=0;i<n;i++)
        {
            int low=sc.nextInt();
            int hig=sc.nextInt();
            int inx=lowerbound(l,l.size(),hig);

            if(inx>=0 && l.get(inx)>=low)
            {  if( (inx+1)<l.size() && l.get(inx+1)==hig )
            {
                 System.out.println(l.get(inx+1));
            }
            else{
                System.out.println(l.get(inx));}
            }
            else{
                 System.out.println(-1);
            }

        }

    }

}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;

public class Main{
    public static LinkedList div(int r)
    {
         LinkedList<Integer> li=new LinkedList<>();
         int rr=(int)Math.sqrt(r);
         for(int i=1;i<=rr;i++)
         {
             if(r%i==0)
             {
                 li.add(i);
                 li.add(r/i);
             }
         }
         if(rr==li.get(li.size()-1)){
             li.remove(li.size()-1);
         }
         Collections.sort(li);
        return li;
    }

    public static int gcd(int m,int n)
    {
        while(n != 0) {
        int t = m % n;
        m = n;
        n = t;
	}

    return m;
    }
    public static int lowerbound(LinkedList<Integer> l,int length,int value)
    {
          int low = 0;
        int high = length;
        while (low < high) {
            final int mid = (low + high) / 2;
            if (value >= l.get(mid)) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;

    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a,b;
        a=sc.nextInt();
        b=sc.nextInt();

        int hd=gcd(a,b);
        LinkedList<Integer> l=new LinkedList<>();
        l=div(hd);

        int n=sc.nextInt();
        for (int i=0;i<n;i++)
        {
            int low=sc.nextInt();
            int hig=sc.nextInt();
            int inx=lowerbound(l,l.size(),hig);
              System.out.print(inx);
            if(l.get(inx-1)>=low && inx>0)
            {
               System.out.println(l.get(inx-1));
            }
            else{
                 System.out.println(-1);
            }

        }

    }

}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;

public class Main{
    public static LinkedList div(int r)
    {
         LinkedList<Integer> li=new LinkedList<>();
         int rr=(int)Math.sqrt(r);
         for(int i=1;i<=rr;i++)
         {
             if(r%i==0)
             {
                 li.add(i);
                 li.add(r/i);
             }
         }
         if(rr==li.get(li.size()-1)){
             li.remove(li.size()-1);
         }
         Collections.sort(li);
        return li;
    }

    public static int gcd(int m,int n)
    {
        while(n != 0) {
        int t = m % n;
        m = n;
        n = t;
	}

    return m;
    }
    public static int lowerbound(LinkedList<Integer> l,int length,int value)
    {
         int low = 0;
        int high = length;
        while (low < high) {
            final int mid = (low + high) / 2;
            //checks if the value is less than middle element of the array
            if (value <= l.get(mid)) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return low-1;

    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int a,b;
        a=sc.nextInt();
        b=sc.nextInt();

        int hd=gcd(a,b);
        LinkedList<Integer> l=new LinkedList<>();
        l=div(hd);

        int n=sc.nextInt();
        for (int i=0;i<n;i++)
        {
            int low=sc.nextInt();
            int hig=sc.nextInt();
            int inx=lowerbound(l,l.size(),hig);

            if(l.get(inx)>=low)
            {
                System.out.println(l.get(inx));
            }
            else{
                 System.out.println(-1);
            }

        }

    }

}


import java.util.*;
public class Solution{
	static Scanner sc = new Scanner(System.in);
	static int GCD(int a,int b){
		if(b==0||a%b==0)
			return b;
		return GCD(b,a%b);
	}
	public static void main(String args[]){
		int a = sc.nextInt(),b = sc.nextInt();
		int t = sc.nextInt();
		ArrayList<Integer>factors = new ArrayList<Integer>();
		int gcd = GCD(a,b);
		for(int i=1;i<=Math.sqrt(gcd);i++){
			if(gcd%i==0){
				factors.add(i);
				if(i!=gcd/i)
					factors.add(gcd/i);
			}
		}
		Collections.sort(factors);
		while(t-->0){
			int l = sc.nextInt(),r = sc.nextInt();
			int cur = -1;
			int high = factors.size()-1,low = 0;
			while(high>=low){
				int mid = (high+low)>>1;
				if(factors.get(mid)>=l&&factors.get(mid)<=r){
					cur = cur<factors.get(mid)?factors.get(mid):cur;
					low = mid+1;
				}
				else if(factors.get(mid)>r)
					high = mid-1;
				else if(factors.get(mid)<l)
					low = mid+1;
			}
			System.out.println(cur);
		}
	}
}


import java.util.*;
public class Solution{
	static Scanner sc = new Scanner(System.in);
	static int GCD(int a,int b){
		if(b==0||a%b==0)
			return b;
		return GCD(b,a%b);
	}
	public static void main(String args[]){
		int a = sc.nextInt(),b = sc.nextInt();
		int t = sc.nextInt();
		ArrayList<Integer>factors = new ArrayList<Integer>();
		int gcd = GCD(a,b);
		for(int i=1;i<=Math.sqrt(gcd);i++){
			if(gcd%i==0){
				factors.add(i);
				if(i!=gcd/i)
					factors.add(gcd/i);
			}
		}
		Collections.sort(factors);
		while(t-->0){
			int l = sc.nextInt(),r = sc.nextInt();
			int cur = -1;
		/*	int high = factors.size()-1,low = 0;
			while(high>=low){
				int mid = (high+low)>>1;
				if(factors.get(mid)>=l&&factors.get(mid)<=r){
					cur = cur<factors.get(mid)?factors.get(mid):cur;
					low = mid+1;
				}
				else if(factors.get(mid)>r)
					high = mid-1;
				else if(factors.get(mid)<l)
					low = mid+1;
			}    */
			for(int i=factors.size()-1;i>-1;i--){
				if(factors.get(i)>=l&&factors.get(i)<=r){
					cur = factors.get(i);
					break;
				}
			}
			System.out.println(cur);
		}
	}
}


/* package codechef; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		ArrayList<Integer> al=new ArrayList<Integer>();
		for(int i=1;i*i<=a;i++){
		    if(i*i==a&&b%i==0){al.add(i);}
		    else if(a%i==0){
		        if(b%i==0)al.add(i);
		        if(b%(a/i)==0)al.add(a/i);
		    }
		}
		Collections.sort(al);
		int t=sc.nextInt();
		for(int l=0;l<t;l++){
		    int lowB=sc.nextInt();
		    int highB=sc.nextInt();
		    int low=0;int high=al.size()-1;
		    int ans=-1;
		    while(low<=high){
		        int mid=low+(high-low)/2;
		        if(al.get(mid)>=lowB&&al.get(mid)<=highB){ans=al.get(mid);low=mid+1;}
		        else if(al.get(mid)<lowB){low=mid+1;}
		        else high=mid-1;
		    }
		    System.out.println(ans);
		}
	}
}


/* package codechef; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		ArrayList<Integer> al=new ArrayList<Integer>();
		for(int i=1;i*i<=a;i++){
		    if(i*i==a){al.add(i);}
		    else if(a%i==0){
		        al.add(i);
		        al.add(a/i);
		    }
		}
		Collections.sort(al);
		int t=sc.nextInt();
		for(int l=0;l<t;l++){
		    int lowB=sc.nextInt();
		    int highB=sc.nextInt();
		    int low=0;int high=al.size()-1;
		    int ans=-1;
		    while(low<=high){
		        int mid=low+(high-low)/2;
		        if(al.get(mid)>=lowB&&al.get(mid)<=highB){ans=al.get(mid);low=mid+1;}
		        else if(al.get(mid)<lowB){low=mid+1;}
		        else high=mid-1;
		    }
		    System.out.println(ans);
		}
	}
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        long[] div = new long[(int)n];
        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                if(i*i != n)
                    div[counter++] = n/i;
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }
    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        long[] div = new long[1000000];
        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                if(i*i != n)
                    div[counter++] = n/i;
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }
    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


//package CodeForces;

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

public class ModifiedGcd {

	static int gcd(int a,int b)
	{
		if(b==0)
		{
			return a;
		}
		if(b>a)
		{
			return gcd(b,a);
		}
		return gcd(b,a%b);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s=new Scanner(System.in);
		int a=s.nextInt();
		int b=s.nextInt();
		int gcd=gcd(a,b);
		ArrayList<Integer> arr=new ArrayList<Integer>();
		for(int i=1;i*i<=gcd;i++)
		{
			if(gcd%i==0)
			{
				arr.add(i);
				if(i*i!=gcd)
				{
					arr.add(gcd/i);
				}
			}
		}

		int q=s.nextInt();
		while(q>0)
		{
			int l=s.nextInt();int h=s.nextInt();
			int ans=-1;
			for(int i=0;i<arr.size();i++)
			{
				if(arr.get(i)>ans&&arr.get(i)>=l&&arr.get(i)<=h)
				{
					ans=arr.get(i);
				}
			}

			System.out.println(ans);
			q--;
		}

	}

}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        long[] div = new long[(int)Math.sqrt(n)];
        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                if(i*i != n)
                    div[counter++] = n/i;
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }
    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        int total_div = 1;

        long temp = n;
        for(int p=2; p*p<=temp; p++){
            if(temp%p == 0){
                int ct = 0;
                while(temp%p == 0){
                    temp /= p;
                    ct++;
                }
                total_div *= (ct+1);
            }

            if(temp > 1)
                total_div *= 2;
        }

       // System.out.println(n);
        //System.out.println(total_div);

        long[] div = new long[total_div+1];

        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                if(i*i != n)
                    div[counter++] = n/i;
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }
    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        int total_div = 1;

        long temp = n;
        for(int p=2; p*p<=temp; p++){
            if(temp%p == 0){
                int ct = 0;
                while(temp%p == 0){
                    temp /= p;
                    ct++;
                }
                total_div *= (ct+1);
            }

            if(temp > 1)
                total_div *= 2;
        }

       // System.out.println(n);
        //System.out.println(total_div);

        long[] div = new long[total_div+1];

        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                //System.out.print(div[counter-1]+ " ");
                if(i*i != n){
                    div[counter++] = n/i;
                  //  System.out.print(div[counter-1]+ " ");
                }
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        int[] dp = new int[100000];
        boolean[] check = new boolean[100000];

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        int c = 0;
        if(L == R){
            if(check[(int)L])
            {
                System.out.println(L);
                continue;
            }
            if(contains(div, L)){
                System.out.println(L);
                check[(int)L] = true;
                continue;
            }
        }

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }

    static boolean contains(long[] div, long L){
        int low = 0;
        int high = div.length-1;
        while(low < high){
            int middle = low + (high-low)/2;
            if(div[middle] == L)
                return true;
            if(div[middle] > L)
                high = middle - 1;
            else
                low = middle + 1;
        }
        return false;
    }

    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        int total_div = 1;

        long temp = n;
        for(int p=2; p*p<=temp; p++){
            if(temp%p == 0){
                int ct = 0;
                while(temp%p == 0){
                    temp /= p;
                    ct++;
                }
                total_div *= (ct+1);
            }
        }

        long[] div = new long[total_div];

        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                if(i*i != n)
                    div[counter++] = n/i;
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }
    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        int total_div = 1;

        long temp = n;
        for(int p=2; p*p<=temp; p++){
            if(temp%p == 0){
                int ct = 0;
                while(temp%p == 0){
                    temp /= p;
                    ct++;
                }
                total_div *= (ct+1);
            }

            if(temp > 1)
                total_div *= 2;
        }

       // System.out.println(n);
        //System.out.println(total_div);

        long[] div = new long[total_div+1];

        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                //System.out.print(div[counter-1]+ " ");
                if(i*i != n){
                    div[counter++] = n/i;
                  //  System.out.print(div[counter-1]+ " ");
                }
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        int[] dp = new int[100000];
        boolean[] check = new boolean[100000];

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        int c = 0;
        if(L == R){
            if(check[L])
            {
                System.out.println(L);
                continue;
            }
            if(contains(div, L)){
                System.out.println(L);
                check[L] = true;
                continue;
            }
        }

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }

    static boolean contains(long[] div, long L){
        int low = 0;
        int high = div.length-1;
        while(low < high){
            int middle = low + (high-low)/2;
            if(div[middle] == L)
                return true;
            if(div[middle] > L)
                high = middle - 1;
            else
                low = middle + 1;
        }
        return false;
    }

    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}


import java.io.*;
import java.util.*;
public class Solution{
    public static void main(String[] args) throws Exception{

        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        String[] i1 = buffer.readLine().split(" ");

        long M = Long.parseLong(i1[0]);
        long N = Long.parseLong(i1[1]);

        long n = gcd(M,N);

        int total_div = 1;

        long temp = n;
        for(int p=2; p*p<=temp; p++){
            if(temp%p == 0){
                int ct = 0;
                while(temp%p == 0){
                    temp /= p;
                    ct++;
                }
                total_div *= (ct+1);
            }

            if(temp > 1)
                total_div *= 2;
        }

       // System.out.println(n);
        //System.out.println(total_div);

        long[] div = new long[total_div+1];

        int counter = 0;

        for(int i=1; i*i<=n; i++){
            if(n%i == 0){
                div[counter++] = i;
                //System.out.print(div[counter-1]+ " ");
                if(i*i != n){
                    div[counter++] = n/i;
                  //  System.out.print(div[counter-1]+ " ");
                }
            }
        }

        int t = Integer.parseInt(buffer.readLine());

        while(t-- > 0){
             String[] i2 = buffer.readLine().split(" ");
        long L = Long.parseLong(i2[0]);
        long R = Long.parseLong(i2[1]);

        if(L == R){
            if(contains(div, L)){
                System.out.println(L);
                continue;
            }
        }

        long res = -1;

        for(int a=0; a<div.length; a++){
            if(div[a] >= L && div[a] <=R){
                res = max(res, div[a]);
            }
        }
        System.out.println(res);
        }
    }

    static boolean contains(long[] div, long L){
        int low = 0;
        int high = div.length-1;
        while(low < high){
            int middle = low + (high-low)/2;
            if(div[middle] == L)
                return true;
            if(div[middle] > L)
                high = middle - 1;
            else
                low = middle + 1;
        }
        return false;
    }

    static long max(long a, long b){
        return a>b?a:b;
    }
    static long gcd(long a, long b){
        if(b == 0)
            return a;
        return gcd(b, a%b);
    }
}