using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Resources;
using System.Text;

namespace Codeforces
{
	class Program
	{
		static void Main(string[] args)
		{
			string input1 = Console.ReadLine();
			string input2 = Console.ReadLine();

			//string input3 = Console.ReadLine();
			//string input4 = Console.ReadLine();

			var inputs1 = input1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
			//var inputs2 = input2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();

			long a = inputs1[0];
			long b = inputs1[1];
			long n = long.Parse(input2);

			var list = new List<Tuple<long,long>>();
			for (long i = 0; i < n; i++)
			{
				var inputs = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
				list.Add(new Tuple<long, long>(inputs[0], inputs[1]));
			}

			var min = Math.Min(a, b);
			var ds = new List<long>();
			for (long i = 2; i <= min / 2; i++)
			{
				if (a % i == 0 && b % i == 0)
				{
					ds.Add(i);
				}
			}

			if (a % min == 0 && b % min == 0)
			{
				ds.Add(min);
			}

			var results = new List<long>();
			foreach (var item in list)
			{
				var dss = ds.Where(i => i >= item.Item1 && i <= item.Item2).ToList();
				if (dss.Count > 0)
				{
					results.Add(dss.LastOrDefault());
				}
				else
				{
					results.Add(-1);
				}
			}

			foreach (var result in results)
			{
				Console.WriteLine(result);
			}
		}

		public static void Print(int[] number)
		{
			var stringBuilder = new StringBuilder();
			foreach (var i in number)
			{
				if (i == 0 && stringBuilder.Length == 0)
				{
					continue;
				}

				stringBuilder.Append(i);
			}

			Console.WriteLine(stringBuilder.ToString());
		}

		public void Method1(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n1 >= n2 || (a >= b && a < 2 * b))
			{

			}
		}

		public void Method2(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n2 >= n1 || (b >= a && b < 2 * a))
			{

			}
		}

		public class Node
		{
			public int Count { get; set; }

			public int FirstIndex { get; set; } = -1;

			public int LastIndex { get; set; } = -1;
		}

		//public class Node<T>
		//{
		//	public Node<T> Left { get; set; }

		//	public Node<T> Right { get; set; }

		//	public T Value { get; set; }

		//	public Node(T value)
		//	{
		//		Value = value;
		//	}
		//}

		//public class Tree<T>
		//{
		//	public Node<T> Root { get; set; }

		//	public Tree(T value)
		//	{
		//		Root = new Node<T>(value);
		//	}
		//}

		private static long GCD(long a, long b)
		{
			long max = Math.Max(a, b);
			long min = Math.Min(a, b);

			if (min == 0)
			{
				return max;
			}

			a = min;
			b = max % min;
			return GCD(a, b);
		}

		private static long LCM(long a, long b)
		{
			return Math.Abs(a * b) / GCD(a, b);
		}

		//private static int Length(short[] a)
		//{
		//	int firstItemIndex = 0;
		//	for (int i = 0; i < a.Length; i++)
		//	{
		//		if (a[i] == 0)
		//		{
		//			continue;
		//		}

		//		firstItemIndex = i;
		//		break;
		//	}

		//	return a.Length - firstItemIndex;
		//}

		//private static short[] Subtract(short[] a, short[] b)
		//{
		//	if (a.Length != b.Length)
		//	{
		//		throw new ArgumentException();
		//	}

		//	short[] result = new short[a.Length];
		//	Array.Copy(a, result, a.Length);
		//	for (int i = result.Length - 1; i >= 0; i--)
		//	{
		//		if (result[i] < b[i])
		//		{
		//			int j = i - 1;
		//			while (result[j] == 0)
		//			{
		//				result[j--] = 9;
		//			}

		//			result[j]--;
		//			result[i] += 10;
		//		}

		//		result[i] -= b[i];
		//	}

		//	return result;
		//}

		//private static short[] Multiply(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	for (int i = a.Length - 1; i > 0; i--)
		//	{
		//		int temp = a[i] * b;
		//		result[i] = (short)(result[i] + temp % 10);
		//		result[i - 1] = (short)(result[i - 1] + temp / 10);
		//	}

		//	return result;
		//}

		//private static int Mod(short[] a, int b)
		//{
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		rest = d % b;
		//		i++;
		//	}

		//	return rest;
		//}

		//private static short[] Divide(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		result[i] = (short)(d / b);
		//		rest = d % b;
		//		i++;
		//	}

		//	return result;
		//}
	}
}


using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Resources;
using System.Text;

namespace Codeforces
{
	class Program
	{
		static void Main(string[] args)
		{
			string input1 = Console.ReadLine();
			string input2 = Console.ReadLine();

			//string input3 = Console.ReadLine();
			//string input4 = Console.ReadLine();

			var inputs1 = input1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
			//var inputs2 = input2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();

			long a = inputs1[0];
			long b = inputs1[1];
			long n = long.Parse(input2);

			var list = new List<Tuple<long,long>>();
			for (long i = 0; i < n; i++)
			{
				var inputs = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
				list.Add(new Tuple<long, long>(inputs[0], inputs[1]));
			}

			var gcd = GCD(a, b);
			var ds = new List<long> { 1 };
			int index = 1;
			long border = gcd / 2;
			for (long i = 2; i <= border; i++)
			{
				if (gcd % i == 0)
				{
					ds.Insert(index, gcd / i);
					ds.Insert(index, i);
					index++;
					border = gcd / i;
				}
			}

			ds.Add(gcd);

			var results = new List<long>();
			foreach (var item in list)
			{
				var dss = ds.Where(i => i >= item.Item1 && i <= item.Item2).ToList();
				if (dss.Count > 0)
				{
					results.Add(dss.LastOrDefault());
				}
				else
				{
					results.Add(-1);
				}
			}

			foreach (var result in results)
			{
				Console.WriteLine(result);
			}
		}

		public static void Print(int[] number)
		{
			var stringBuilder = new StringBuilder();
			foreach (var i in number)
			{
				if (i == 0 && stringBuilder.Length == 0)
				{
					continue;
				}

				stringBuilder.Append(i);
			}

			Console.WriteLine(stringBuilder.ToString());
		}

		public void Method1(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n1 >= n2 || (a >= b && a < 2 * b))
			{

			}
		}

		public void Method2(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n2 >= n1 || (b >= a && b < 2 * a))
			{

			}
		}

		public class Node
		{
			public int Count { get; set; }

			public int FirstIndex { get; set; } = -1;

			public int LastIndex { get; set; } = -1;
		}

		//public class Node<T>
		//{
		//	public Node<T> Left { get; set; }

		//	public Node<T> Right { get; set; }

		//	public T Value { get; set; }

		//	public Node(T value)
		//	{
		//		Value = value;
		//	}
		//}

		//public class Tree<T>
		//{
		//	public Node<T> Root { get; set; }

		//	public Tree(T value)
		//	{
		//		Root = new Node<T>(value);
		//	}
		//}

		private static long GCD(long a, long b)
		{
			long max = Math.Max(a, b);
			long min = Math.Min(a, b);

			if (min == 0)
			{
				return max;
			}

			a = min;
			b = max % min;
			return GCD(a, b);
		}

		private static long LCM(long a, long b)
		{
			return Math.Abs(a * b) / GCD(a, b);
		}

		//private static int Length(short[] a)
		//{
		//	int firstItemIndex = 0;
		//	for (int i = 0; i < a.Length; i++)
		//	{
		//		if (a[i] == 0)
		//		{
		//			continue;
		//		}

		//		firstItemIndex = i;
		//		break;
		//	}

		//	return a.Length - firstItemIndex;
		//}

		//private static short[] Subtract(short[] a, short[] b)
		//{
		//	if (a.Length != b.Length)
		//	{
		//		throw new ArgumentException();
		//	}

		//	short[] result = new short[a.Length];
		//	Array.Copy(a, result, a.Length);
		//	for (int i = result.Length - 1; i >= 0; i--)
		//	{
		//		if (result[i] < b[i])
		//		{
		//			int j = i - 1;
		//			while (result[j] == 0)
		//			{
		//				result[j--] = 9;
		//			}

		//			result[j]--;
		//			result[i] += 10;
		//		}

		//		result[i] -= b[i];
		//	}

		//	return result;
		//}

		//private static short[] Multiply(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	for (int i = a.Length - 1; i > 0; i--)
		//	{
		//		int temp = a[i] * b;
		//		result[i] = (short)(result[i] + temp % 10);
		//		result[i - 1] = (short)(result[i - 1] + temp / 10);
		//	}

		//	return result;
		//}

		//private static int Mod(short[] a, int b)
		//{
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		rest = d % b;
		//		i++;
		//	}

		//	return rest;
		//}

		//private static short[] Divide(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		result[i] = (short)(d / b);
		//		rest = d % b;
		//		i++;
		//	}

		//	return result;
		//}
	}
}


using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Resources;
using System.Text;

namespace Codeforces
{
	class Program
	{
		static void Main(string[] args)
		{
			string input1 = Console.ReadLine();
			string input2 = Console.ReadLine();

			//string input3 = Console.ReadLine();
			//string input4 = Console.ReadLine();

			var inputs1 = input1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
			//var inputs2 = input2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();

			long a = inputs1[0];
			long b = inputs1[1];
			long n = long.Parse(input2);

			var list = new List<Tuple<long,long>>();
			for (long i = 0; i < n; i++)
			{
				var inputs = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray();
				list.Add(new Tuple<long, long>(inputs[0], inputs[1]));
			}

			var gcd = GCD(a, b);
			var ds = new List<long>();
			int index = 0;
			long border = gcd / 2;
			for (long i = 2; i <= border; i++)
			{
				if (gcd % i == 0)
				{
					ds.Insert(index, gcd / i);
					ds.Insert(index, i);
					index++;
					border = gcd / i;
				}
			}

			ds.Add(gcd);

			var results = new List<long>();
			foreach (var item in list)
			{
				var dss = ds.Where(i => i >= item.Item1 && i <= item.Item2).ToList();
				if (dss.Count > 0)
				{
					results.Add(dss.LastOrDefault());
				}
				else
				{
					results.Add(-1);
				}
			}

			foreach (var result in results)
			{
				Console.WriteLine(result);
			}
		}

		public static void Print(int[] number)
		{
			var stringBuilder = new StringBuilder();
			foreach (var i in number)
			{
				if (i == 0 && stringBuilder.Length == 0)
				{
					continue;
				}

				stringBuilder.Append(i);
			}

			Console.WriteLine(stringBuilder.ToString());
		}

		public void Method1(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n1 >= n2 || (a >= b && a < 2 * b))
			{

			}
		}

		public void Method2(ref int n1, ref int n2, ref int k1, ref int k2)
		{
			double a = (double)n1 / k1;
			double b = (double)n2 / k2;
			if (n2 >= n1 || (b >= a && b < 2 * a))
			{

			}
		}

		public class Node
		{
			public int Count { get; set; }

			public int FirstIndex { get; set; } = -1;

			public int LastIndex { get; set; } = -1;
		}

		//public class Node<T>
		//{
		//	public Node<T> Left { get; set; }

		//	public Node<T> Right { get; set; }

		//	public T Value { get; set; }

		//	public Node(T value)
		//	{
		//		Value = value;
		//	}
		//}

		//public class Tree<T>
		//{
		//	public Node<T> Root { get; set; }

		//	public Tree(T value)
		//	{
		//		Root = new Node<T>(value);
		//	}
		//}

		private static long GCD(long a, long b)
		{
			long max = Math.Max(a, b);
			long min = Math.Min(a, b);

			if (min == 0)
			{
				return max;
			}

			a = min;
			b = max % min;
			return GCD(a, b);
		}

		private static long LCM(long a, long b)
		{
			return Math.Abs(a * b) / GCD(a, b);
		}

		//private static int Length(short[] a)
		//{
		//	int firstItemIndex = 0;
		//	for (int i = 0; i < a.Length; i++)
		//	{
		//		if (a[i] == 0)
		//		{
		//			continue;
		//		}

		//		firstItemIndex = i;
		//		break;
		//	}

		//	return a.Length - firstItemIndex;
		//}

		//private static short[] Subtract(short[] a, short[] b)
		//{
		//	if (a.Length != b.Length)
		//	{
		//		throw new ArgumentException();
		//	}

		//	short[] result = new short[a.Length];
		//	Array.Copy(a, result, a.Length);
		//	for (int i = result.Length - 1; i >= 0; i--)
		//	{
		//		if (result[i] < b[i])
		//		{
		//			int j = i - 1;
		//			while (result[j] == 0)
		//			{
		//				result[j--] = 9;
		//			}

		//			result[j]--;
		//			result[i] += 10;
		//		}

		//		result[i] -= b[i];
		//	}

		//	return result;
		//}

		//private static short[] Multiply(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	for (int i = a.Length - 1; i > 0; i--)
		//	{
		//		int temp = a[i] * b;
		//		result[i] = (short)(result[i] + temp % 10);
		//		result[i - 1] = (short)(result[i - 1] + temp / 10);
		//	}

		//	return result;
		//}

		//private static int Mod(short[] a, int b)
		//{
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		rest = d % b;
		//		i++;
		//	}

		//	return rest;
		//}

		//private static short[] Divide(short[] a, int b)
		//{
		//	short[] result = new short[a.Length];
		//	int rest = 0, i = 0;
		//	while (i < a.Length)
		//	{
		//		int d = 10 * rest + a[i];
		//		while (d < b && i < a.Length - 1)
		//		{
		//			d = 10 * d + a[++i];
		//		}

		//		result[i] = (short)(d / b);
		//		rest = d % b;
		//		i++;
		//	}

		//	return result;
		//}
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Contest_75
{
    class Program
    {
        static void B()
        {
            string name = Console.ReadLine();
            int n = int.Parse(Console.ReadLine());

            Dictionary<string, int> friends = new Dictionary<string, int>();
            friends.Add("", 0);

            for (int i = 0; i < n; i++)
            {
                var t = Console.ReadLine().Split(' ');
                int k = 5;
                string a = t[0];
                string b;
                switch (t[1][0])
                {
                    case 'p':
                    case 'c':
                        if (t[1][0] == 'p')
                            k = 15;
                        k = 10;

                        b = t[3].Split('\'')[0];
                        break;
                    default:
                        b = t[2].Split('\'')[0];
                        break;
                }
                string s = "";
                if (a == name)
                    s = b;
                if (b == name)
                    s = a;
                try
                {
                    friends.Add(a, 0);
                }
                catch (Exception)
                {
                }
                try
                {
                    friends.Add(b, 0);
                }
                catch (Exception)
                {
                }
                friends[s] += k;
            }

            try
            {
                friends.Remove("");
                friends.Remove(name);
            }
            catch (Exception)
            {
            }

            //var dict = (from f in friends orderby f.Value, f.Key select f);
            //var d = friends.OrderByDescending(a => a, new Comparer());
            var d = friends.OrderByDescending(a => a.Value).ThenBy(a => a.Key);

            foreach (var e in d)
            {
                Console.WriteLine(e.Key);
            }
        }

        public class Comparer : IComparer<KeyValuePair<string, int>>
        {
            public int Compare(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
            {
                if (x.Value == y.Value)
                    return string.Compare(y.Key, x.Key, StringComparison.OrdinalIgnoreCase);
                if (x.Value < y.Value)
                    return -1;
                if (x.Value > y.Value)
                    return 1;
                return 0;
            }
        }

        static List<int> r = new List<int>();
        static List<int> mn;
        static void pr(int k, int s)
        {
            for (int i = k; i < mn.Count; i++)
            {
                s *= mn[i];
                if (r.IndexOf(s) == -1)
                    r.Add(s);
                pr(i + 1, s);
                s /= mn[i];
            }
        }

        static List<int> inter(List<int> a, List<int> b)
        {
            List<int> res = new List<int>();
            foreach (var x in a)
            {
                if (b.IndexOf(x) > -1)
                {
                    res.Add(x);
                    b.Remove(x);
                }
            }
            return res;
        }

        static int NOD(int a, int b)
        {
            while (a != b)
            {
                if (a > b)
                    a -= b;
                else
                    b -= a;
            }
            return a;
        }

        static void C()
        {
            var t = Console.ReadLine().Split(' ');
            int a = int.Parse(t[0]);
            int b = int.Parse(t[1]);
            int n = int.Parse(Console.ReadLine());

            mn = new List<int>();

            mn.Add(1);

            a = NOD(a, b);
            while (a % 2 == 0)
            {
                mn.Add(2);
                a /= 2;
            }

            for (int i = 3; a > 1; i+=2)
            {
                while (a % i == 0)
                {
                    mn.Add(i);
                    a /= i;
                }
            }
            pr(0, 1);
            r.Sort();
            r.Reverse();
            for (int i = 0; i < n; i++)
            {
                t = Console.ReadLine().Split(' ');

                a = int.Parse(t[0]);
                b = int.Parse(t[1]);

                bool ok = true;
                foreach (var k in r)
                {
                    if ((k >= a) && (k <= b))
                    {
                        ok = false;
                        Console.WriteLine(k);
                        break;
                    }
                }
                if (ok)
                    Console.WriteLine(-1);
            }

        }

        static void C_1()
        {
            TextWriter tw = new StreamWriter(@"primes.txt");

            for (long i = 3; i < 1000000000; i += 2)
            {
                bool ok = true;
                for (long j = 2; j < Math.Sqrt(i) + 1; j++)
                {
                    if (i % j == 0)
                    {
                        ok = false;
                        break;
                    }
                }
                if (ok)
                {
                    tw.Write(i + ",");
                }
            }
            tw.Close();
        }

        static void Main(string[] args)
        {
            C();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Contest_75
{
    class Program
    {
        static void B()
        {
            string name = Console.ReadLine();
            int n = int.Parse(Console.ReadLine());

            Dictionary<string, int> friends = new Dictionary<string, int>();
            friends.Add("", 0);

            for (int i = 0; i < n; i++)
            {
                var t = Console.ReadLine().Split(' ');
                int k = 5;
                string a = t[0];
                string b;
                switch (t[1][0])
                {
                    case 'p':
                    case 'c':
                        if (t[1][0] == 'p')
                            k = 15;
                        k = 10;

                        b = t[3].Split('\'')[0];
                        break;
                    default:
                        b = t[2].Split('\'')[0];
                        break;
                }
                string s = "";
                if (a == name)
                    s = b;
                if (b == name)
                    s = a;
                try
                {
                    friends.Add(a, 0);
                }
                catch (Exception)
                {
                }
                try
                {
                    friends.Add(b, 0);
                }
                catch (Exception)
                {
                }
                friends[s] += k;
            }

            try
            {
                friends.Remove("");
                friends.Remove(name);
            }
            catch (Exception)
            {
            }

            //var dict = (from f in friends orderby f.Value, f.Key select f);
            //var d = friends.OrderByDescending(a => a, new Comparer());
            var d = friends.OrderByDescending(a => a.Value).ThenBy(a => a.Key);

            foreach (var e in d)
            {
                Console.WriteLine(e.Key);
            }
        }

        public class Comparer : IComparer<KeyValuePair<string, int>>
        {
            public int Compare(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
            {
                if (x.Value == y.Value)
                    return string.Compare(y.Key, x.Key, StringComparison.OrdinalIgnoreCase);
                if (x.Value < y.Value)
                    return -1;
                if (x.Value > y.Value)
                    return 1;
                return 0;
            }
        }

        static List<int> r = new List<int>();
        static List<int> mn;
        static void pr(int k, int s)
        {
            for (int i = k; i < mn.Count; i++)
            {
                s *= mn[i];
                if (r.IndexOf(s) == -1)
                    r.Add(s);
                pr(i + 1, s);
                s /= mn[i];
            }
        }

        static List<int> inter(List<int> a, List<int> b)
        {
            List<int> res = new List<int>();
            foreach (var x in a)
            {
                if (b.IndexOf(x) > -1)
                {
                    res.Add(x);
                    b.Remove(x);
                }
            }
            return res;
        }

        static void C()
        {
            var t = Console.ReadLine().Split(' ');
            int a = int.Parse(t[0]);
            int b = int.Parse(t[1]);
            int n = int.Parse(Console.ReadLine());

            List<int> ma = new List<int>();
            List<int> mb = new List<int>();

            ma.Add(1); mb.Add(1);
            for (int i = 2; a > 1; i++)
            {
                while (a % i == 0)
                {
                    ma.Add(i);
                    a /= i;
                }
            }
            for (int i = 2; b > 1; i++)
            {
                while (b % i == 0)
                {
                    mb.Add(i);
                    b /= i;
                }
            }

            //mn = ma.Intersect(mb).ToList<int>();
            mn = inter(ma, mb);
            pr(0, 1);
            r.Sort();
            r.Reverse();
            for (int i = 0; i < n; i++)
            {
                t = Console.ReadLine().Split(' ');

                a = int.Parse(t[0]);
                b = int.Parse(t[1]);

                bool ok = true;
                foreach (var k in r)
                {
                    if ((k >= a) && (k <= b))
                    {
                        ok = false;
                        Console.WriteLine(k);
                        break;
                    }
                }
                if (ok)
                    Console.WriteLine(-1);
            }
        }

        static void Main(string[] args)
        {
            C();
        }
    }
}


use std::cmp::Ordering;
use std::io;
use std::str;

pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn get_divisors(n: i64) -> Vec<i64> {
    let mut divisors = vec![1];
    if n > 1 {
        divisors.push(n);
    }
    let mut d = 2;
    while d * d <= n {
        if n % d == 0 {
            divisors.push(d);
            if d * d < n {
                divisors.push(n / d);
            }
        }
        d += 1;
    }
    divisors.sort();
    divisors
}

fn intersect(arr1: &[i64], arr2: &[i64]) -> Vec<i64> {
    let mut ans = Vec::new();
    let mut i = 0;
    let mut j = 0;
    let n1 = arr1.len();
    let n2 = arr2.len();
    while i < n1 && j < n2 {
        match arr1[i].cmp(&arr2[j]) {
            Ordering::Less => i += 1,
            Ordering::Greater => j += 1,
            Ordering::Equal => {
                ans.push(arr1[i]);
                i += 1;
                j += 1;
            }
        }
    }
    ans
}

fn lower_bound(arr: &[i64], target: i64) -> usize {
    let mut lo = 0;
    let mut hi = arr.len();
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if arr[mid] >= target {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }
    lo
}

// Find divisors in [low, high]
fn max_bounded_gcd(common_divisors: &[i64], low: i64, high: i64) -> i64 {
    let lb1 = lower_bound(common_divisors, low);
    let lb2 = lower_bound(common_divisors, high + 1);
    if lb2 - lb1 > 0 {
        common_divisors[lb2 - 1]
    } else {
        -1
    }
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let a: i64 = scan.token();
    let b: i64 = scan.token();

    let divisors_a = get_divisors(a);
    let divisors_b = get_divisors(b);

    let common_divisors = intersect(&divisors_a, &divisors_b);
    let t: i64 = scan.token();
    for _ in 0..t {
        let low: i64 = scan.token();
        let high: i64 = scan.token();
        let ans = max_bounded_gcd(&common_divisors, low, high);
        writeln!(out, "{}", ans).ok();
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}


package main

import (
  "os"
  "bufio"
  "sort"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  a, b := getI(), getI()
  if a > b {
    a, b = b, a
  }
  isFactor := map[int]bool{}
  for d := 1; d*d <= a; d++ {
    if a%d == 0 && b%d == 0 {
      isFactor[d] = true
      c := a/d
      if b%c == 0 {
        isFactor[c] = true
      }
    }
  }
  factors := []int{}
  for factor := range isFactor {
    factors = append(factors, factor)
  }
  sort.Ints(factors)
  n := getI()
  for i := 0; i < n; i++ {
    low, high := getI(), getI()
    result := -1
    for j := len(factors)-1; j >= 0; j-- {
      d := factors[j]
      if low <= d && d <= high {
        result = d
        break
      }
    }
    writer.WriteString(fmt.Sprintf("%d\n", result))
  }
}


package main

import (
  "os"
  "bufio"
  "sort"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  a, b := getI(), getI()
  if a > b {
    a, b = b, a
  }
  isFactor := map[int]bool{}
  for d := 1; d*d <= a; d++ {
    if a%d == 0 && b%d == 0 {
      isFactor[d] = true
      isFactor[a/d] = true
      isFactor[b/d] = true
    }
  }
  factors := []int{}
  for factor := range isFactor {
    factors = append(factors, factor)
  }
  sort.Ints(factors)
  n := getI()
  for i := 0; i < n; i++ {
    low, high := getI(), getI()
    result := -1
    for j := len(factors)-1; j >= 0; j-- {
      d := factors[j]
      if low <= d && d <= high {
        result = d
        break
      }
    }
    writer.WriteString(fmt.Sprintf("%d\n", result))
  }
}


package main

import (
  "os"
  "bufio"
  "sort"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  a, b := getI(), getI()
  if a > b {
    a, b = b, a
  }
  isFactor := map[int]bool{}
  for d := 1; d*d <= a; d++ {
    if a%d == 0 {
      if b%d == 0 {
        isFactor[d] = true
      }
      c := a/d
      if b%c == 0 {
        isFactor[c] = true
      }
    }
  }
  factors := []int{}
  for d := range isFactor {
    factors = append(factors, d)
  }
  sort.Ints(factors)
  for _, d := range factors {
    fmt.Fprintf(os.Stderr, "%d ", d)
  }
  fmt.Fprintf(os.Stderr, "\n")
  n := getI()
  for i := 0; i < n; i++ {
    low, high := getI(), getI()
    result := -1
    for j := len(factors)-1; j >= 0; j-- {
      d := factors[j]
      if low <= d && d <= high {
        result = d
        break
      }
    }
    writer.WriteString(fmt.Sprintf("%d\n", result))
  }
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func CF75C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	gcd := func(a, b int) int {
		for a != 0 {
			a, b = b%a, a
		}
		return b
	}

	var l, r, q int
	Fscan(in, &l, &r, &q)
	g := gcd(l, r)
	ds := []int{}
	for d := 1; d*d <= g; d++ {
		if g%d == 0 {
			ds = append(ds, d)
			if d*d < g {
				ds = append(ds, g/d)
			}
		}
	}
	sort.Ints(ds)
	for ; q > 0; q-- {
		Fscan(in, &l, &r)
		if i := sort.SearchInts(ds, r+1); i > 0 && ds[i-1] >= l {
			Fprintln(out, ds[i-1])
		} else {
			Fprintln(out, -1)
		}
	}
}

func main() { CF75C(os.Stdin, os.Stdout) }


<?php
    //error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    //error_reporting(E_ALL ^ E_DEPRECATED);
    //$in = fopen("input.in", "r");
    $in = fopen("php://stdin", "r");
    $arr = split(" ", fgets($in));
    $n = fgets($in);
    $g = gcd($arr[0], $arr[1]);
    for($i = 1; $i * $i <= $g; $i++)
        if($g % $i == 0)
        {
            $j = $g / $i;
            $u[] = $i;
            if($i != $j) $u[] = $j;
        }
    for($i = 0; $i < $n; $i++)
    {
        $array = split(" ", fgets($in));
        $res = -1;
        for($j = 0; $j < count($u); $j++)
            if($array[0] <= $u[$j] && $u[$j] <= $array[1]) $res = max($res, $u[$j]);
        echo $res . "\n";
    }
    function gcd($a, $b)
    {
        return $b == 0 ? $a : gcd($b, $a % $b);
    }


<?php
    //error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    //error_reporting(E_ALL ^ E_DEPRECATED);
    //$in = fopen("input.in", "r");
    $in = fopen("php://stdin", "r");
    $arr = split(" ", fgets($in));
    $n = fgets($in);
    $g = gcd($arr[0], $arr[1]);
    for($i = 1; $i * $i <= $g; $i++)
        if($g % $i == 0)
        {
            $j = $g / $i;
            if($i != 1) $u[] = $i;
            if($i != $j && $j != 1) $u[] = $j;
        }
    for($i = 0; $i < $n; $i++)
    {
        $array = split(" ", fgets($in));
        $res = -1;
        for($j = 0; $j < count($u); $j++)
            if($array[0] <= $u[$j] && $u[$j] <= $array[1]) $res = max($res, $u[$j]);
        echo $res . "\n";
    }
    function gcd($a, $b)
    {
        return $b == 0 ? $a : gcd($b, $a % $b);
    }


<?php
    //error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    error_reporting(E_ALL ^ E_DEPRECATED);
    //$in = fopen("input.in", "r");
    $in = fopen("php://stdin", "r");
    $arr = split(" ", fgets($in));
    $n = fgets($in);
    $g = gcd($arr[0], $arr[1]);
    for($i = 1; $i * $i <= $g; $i++)
        if($g % $i == 0)
        {
            $j = $g / $i;
            $u[] = $i;
            if($i != $j) $u[] = $j;
        }
    sort($u);
    for($i = 0; $i < $n; $i++)
    {
        $array = split(" ", fgets($in));
        $low = 0; $high = count($u) - 1;
        while($low < $high)
        {
            $mid = ($low + $high + 1) / 2;
            if($u[$mid] <= $array[1]) $low = $mid;
            else $high = $mid - 1;
        }
        if($array[0] <= $u[$low] && $u[$low] <= $array[1]) echo $u[$low] . "\n";
        else echo "-1\n";
    }
    function gcd($a, $b)
    {
        return $b == 0 ? $a : gcd($b, $a % $b);
    }


<?php
    //error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    //error_reporting(E_ALL ^ E_DEPRECATED);
    //$in = fopen("input.in", "r");
    $in = fopen("php://stdin", "r");
    $arr = split(" ", fgets($in));
    $n = fgets($in);
    $g = gcd($arr[0], $arr[1]);
    for($i = 1; $i * $i <= $g; $i++)
        if($g % $i == 0)
        {
            $j = $g / $i;
            $u[] = $i;
            if($i != $j) $u[] = $j;
        }
    sort($u);
    for($i = 0; $i < $n; $i++)
    {
        $array = split(" ", fgets($in));
        $low = 0; $high = count($u) - 1;
        while($low < $high)
        {
            $mid = ($low + $high + 1) / 2;
            if($u[$mid] <= $array[1]) $low = $mid;
            else $high = $mid - 1;
        }
        if($array[0] <= $u[$low] && $u[$low] <= $array[1]) echo $u[$low] . "\n";
        else echo "-1\n";
    }
    function gcd($a, $b)
    {
        return $b == 0 ? $a : gcd($b, $a % $b);
    }


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def find(x):
    l = -1
    r = len(divs)
    while r - l > 1:
        mid = (l + r) / 2
        if divs[mid] <= x:
            l = mid
        else:
            r = mid
    return divs[l]

a, b = map(int, raw_input().split())
m = gcd(a, b)
divs = [1, m]
d = 2
while d * d < m:
    if m % d == 0:
        divs.append(d)
        divs.append(m / d)
    d += 1
if d * d == m:
    divs.append(d)
divs.sort()

q = input()
for _ in range(q):
    l, h = map(int, raw_input().split())
    resp = find(h)
    if resp >= l:
        print(resp)
    else:
        print(-1)


# Problem : C. Modified GCD
# Contest : Codeforces Beta Round #67 (Div. 2)
# URL : https://codeforces.com/contest/75/problem/C
# Memory Limit : 256 MB
# Time Limit : 2000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)

"""
// Author : snape_here - Susanta Mukherjee

 """

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

mod=1000000007

import math

import bisect

def main():

	a,b=mi()
	c=gcd(a,b)
	l=[]
	for i in range(1,int(math.sqrt(c))+1):
		if c%i==0:
			if c//i==i:
				l.append(i)
			else:
				l.append(i)
				l.append(c//i)
	l.sort()
	for _ in range(ii()):
		lo,hi=mi()
		ind=bisect.bisect_right(l,hi)
		ans=l[ind-1]
		if ans<lo:
			print(-1)
		else:
			print(ans)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()


# Problem : C. Modified GCD
# Contest : Codeforces Beta Round #67 (Div. 2)
# URL : https://codeforces.com/contest/75/problem/C
# Memory Limit : 256 MB
# Time Limit : 2000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)

"""
// Author : snape_here - Susanta Mukherjee

 """

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

mod=1000000007

import math

import bisect

def main():

	c,b=mi()
	l=[]
	for i in range(1,int(math.sqrt(c))+1):
		if c%i==0:
			if c//i==i:
				l.append(i)
			else:
				l.append(i)
				l.append(c//i)
	l.sort()
	for _ in range(ii()):
		lo,hi=mi()
		ind=bisect.bisect_right(l,hi)
		ans=l[ind-1]
		if ans<lo:
			print(-1)
		else:
			print(ans)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()


import math
def factorize(n):
	factors = []
	s = int(math.ceil(math.sqrt(n)))
	for i in xrange(1,s+1):
		if n%i==0:
			factors.append(i)
			if n/i != i :
				factors.append(n/i)
	factors.sort()
	return factors
def intersection(a,b):
	return list(set(a)&set(b))
#-------------------------------------------------------
a,b = map(int,raw_input().split())
n = int(raw_input())
low =[]
high=[]
divisor = intersection(factorize(a),factorize(b))
for i in xrange(n):
	a,b = map(int,raw_input().split())
	low.append(a)
	high.append(b)
for i in xrange(n):
	div_set = []
	for element in divisor:
		if element<=high[i] and element>=low[i]:
			div_set.append(element)
	if len(div_set)==0:
		print -1
	else:
		print max(div_set)


import math
def factorize(n):
	factors = []
	s = int(math.ceil(math.sqrt(n)))
	for i in xrange(1,s+1):
		if n%i==0:
			factors.append(i)
			if n/i != i :
				factors.append(n/i)
	factors.sort()
	return factors
def intersection(a,b):
	c = list(set(a)&set(b))
	c.remove(1)
	return c
#-------------------------------------------------------
a,b = map(int,raw_input().split())
n = int(raw_input())
low =[]
high=[]
divisor = intersection(factorize(a),factorize(b))
for i in xrange(n):
	a,b = map(int,raw_input().split())
	low.append(a)
	high.append(b)
for i in xrange(n):
	div_set = []
	for element in divisor:
		if element<=high[i] and element>=low[i]:
			div_set.append(element)
	if len(div_set)==0:
		print -1
	else:
		print max(div_set)


a,b=map(int,raw_input().split())
q=input()
from fractions import gcd
from math import *
g=gcd(a,b)
ans=[]
for i in range(1,int(sqrt(g)+2)):
  if g%i==0:
    ans.append(i)
    ans.append(g/i)
ans.sort()
#print ans
from bisect import *
for _ in range(0,q):
  l,r=map(int,raw_input().split())

  if bisect_left(ans,l)-1<len(ans):
    x=ans[bisect(ans,r)-1]
    #print x
   # print x
    if   x>=l and x<=r:
      print x
    else:
      print -1
  else:
    print -1


a,b=map(int,raw_input().split())
q=input()
from fractions import gcd
from math import *
g=gcd(a,b)
ans=[]
for i in range(1,int(sqrt(g)+2)):
  if g%i==0:
    ans.append(i)
    ans.append(g/i)
ans.sort()
#print ans
from bisect import *
for _ in range(0,q):
  l,r=map(int,raw_input().split())

  if bisect_left(ans,l)<len(ans):
    x=ans[bisect_left(ans,l)]
   # print x
    if   x>=l and x<=r:
      print x
    else:
      print -1
  else:
    print -1


a,b=map(int,raw_input().split())
q=input()
from fractions import gcd
from math import *
g=gcd(a,b)
ans=[]
for i in range(1,int(sqrt(g)+2)):
  if g%i==0:
    ans.append(i)
    ans.append(g/i)
ans.sort()
#print ans
from bisect import *
for _ in range(0,q):
  l,r=map(int,raw_input().split())

  if bisect_left(ans,l)-1<len(ans):
    x=ans[bisect_left(ans,r)-1]
    #print x
   # print x
    if   x>=l and x<=r:
      print x
    else:
      print -1
  else:
    print -1


import sys
if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

    sys.stdin = io.BytesIO(sys.stdin.read())
    input = lambda: sys.stdin.readline().rstrip()

RS = raw_input
RI = lambda x=int: map(x,RS().split())
RN = lambda x=int: x(RS())
''' ...................................................................... '''

def factor(num):
    i = 1
    fac = set()
    while i*i<=num:
        if num%i==0:
            fac.add(i)
            fac.add(num/i)
        i+=1
    return fac

a,b = RI()
facA = factor(a)
facB = factor(b)
common = facA&facB

for _ in xrange(RN()):
    lo,hi = RI()
    ans = -1
    while lo<=hi:
        mid = (lo+hi)/2
        if mid in common:
            ans = mid
            lo = mid+1
        else: hi = mid-1
    print ans


import sys
if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

    sys.stdin = io.BytesIO(sys.stdin.read())
    input = lambda: sys.stdin.readline().rstrip()

RS = raw_input
RI = lambda x=int: map(x,RS().split())
RN = lambda x=int: x(RS())
''' ...................................................................... '''

def factor(num):
    i = 1
    fac = set()
    while i*i<=num:
        if num%i==0:
            fac.add(i)
            fac.add(num/i)
        i+=1
    return fac

a,b = RI()
facA = factor(a)
facB = factor(b)
common = facA&facB

for _ in xrange(RN()):
    lo,hi = RI()
    ans = -1
    for f in common:
        if lo<=f<=hi:
            ans = max(ans,f)
    print ans


import sys
if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

    sys.stdin = io.BytesIO(sys.stdin.read())
    input = lambda: sys.stdin.readline().rstrip()

RS = raw_input
RI = lambda x=int: map(x,RS().split())
RN = lambda x=int: x(RS())
''' ...................................................................... '''

def factor(num):
    i = 1
    fac = set()
    while i*i<=num:
        if num%i==0:
            fac.add(i)
            fac.add(num/i)
        i+=1
    return fac

def find(arr,m,M):
    lo,hi = 0,len(arr)-1
    ans = -1
    while lo<=hi:
        mid = (lo+hi)/2

        if arr[mid]<m:
            lo = mid+1
        elif arr[mid]>M:
            hi = mid-1
        else:
            ans = arr[mid]
            lo = mid+1
    return ans

a,b = RI()
facA = factor(a)
facB = factor(b)
common = sorted(facA&facB)

for _ in xrange(RN()):
    lo,hi = RI()
    print find(common,lo,hi)


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <27/Mar/2019 07:03:51 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def main():
    a, b = get_ints()
    from math import gcd, sqrt
    x = gcd(a, b)
    divisors = []
    i = 1
    while i <= sqrt(x):
        if (x % i == 0):
            if (x//i == i):
                divisors.append(i)
            else:
                divisors.append(i)
                divisors.append(x//i)
        i += 1
    divisors.sort()
    # print(divisors)

    n = len(divisors)
    from bisect import bisect_left
    for tc in range(int(input())):
        low, high = get_ints()
        l = bisect_left(divisors, low)
        r = bisect_left(divisors, high)
        if l == n:
            print(-1)
            continue

        if r == n or (r < n and divisors[r] != high):
            r -= 1

        if r >= l:
            print(divisors[r])
        else:
            print(-1)

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <27/Mar/2019 06:52:28 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def main():
    a, b = get_ints()

    divisors = []

    for i in range(1, a+1):
        if a % i == 0 and b % i == 0:
            divisors.append(i)
    n = len(divisors)
    from bisect import bisect_left
    for tc in range(int(input())):
        low, high = get_ints()
        l = bisect_left(divisors, low)
        r = bisect_left(divisors, high)

        if l == n:
            print(-1)
            continue

        if r == n or (r < n and divisors[r] != high):
            r -= 1

        if r >= l:
            print(divisors[r])
        else:
            print(-1)

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <27/Mar/2019 06:55:06 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def main():
    a, b = get_ints()

    divisors = []

    for i in range(1, a+1):
        if a % i == 0 and b % i == 0:
            divisors.append(i)
    n = len(divisors)
    from bisect import bisect_left
    d = {}
    for tc in range(int(input())):
        low, high = get_ints()
        l = bisect_left(divisors, low)
        r = bisect_left(divisors, high)
        if (l, r) in d:
            print(d[(l, r)])
            continue
        if l == n:
            print(-1)
            d[(l, r)] = -1
            continue

        if r == n or (r < n and divisors[r] != high):
            r -= 1

        if r >= l:
            print(divisors[r])
            d[(l, r)] = divisors[r]
        else:
            print(-1)
            d[(l, r)] = -1

if __name__ == "__main__":
    main()


#	!/usr/bin/env python3
#	encoding: UTF-8
#	Modified: <27/Mar/2019 06:56:22 PM>

#	✪ H4WK3yE乡
#	Mohd. Farhan Tahir
#	Indian Institute Of Information Technology (IIIT),Gwalior

# ///==========Libraries, Constants and Functions=============///

import sys

inf = float("inf")
mod = 1000000007

def get_array(): return list(map(int, sys.stdin.readline().split()))

def get_ints(): return map(int, sys.stdin.readline().split())

def input(): return sys.stdin.readline()

# ///==========MAIN=============///

def main():
    a, b = get_ints()

    divisors = []

    for i in range(1, a+1):
        if a % i == 0 and b % i == 0:
            divisors.append(i)
    n = len(divisors)
    from bisect import bisect_left
    d = {}
    for tc in range(int(input())):
        low, high = get_ints()
        l = bisect_left(divisors, low)
        r = bisect_left(divisors, high)
        if (low, high) in d:
            print(d[(low, high)])
            continue
        if l == n:
            print(-1)
            d[(low, high)] = -1
            continue

        if r == n or (r < n and divisors[r] != high):
            r -= 1

        if r >= l:
            print(divisors[r])
            d[(low, high)] = divisors[r]
        else:
            print(-1)
            d[(low, high)] = -1

if __name__ == "__main__":
    main()


# import sys

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

def gcd(num1, num2):
	if num2 == 0:
		return num1

	return gcd(num2, num1 % num2)

def binary_s(left, right):
	le = 0
	ri = len(res1) - 1

	while le <= ri:
		mid = le + (ri - le)//2

		if res1[mid] > right:
			ri = mid - 1
		elif mid + 1 == len(res1) or res1[mid + 1] > right:
			if le <= ri:
				return -1 if res1[mid] < left or res1[mid] > right else res1[mid]
		else:
			le = mid + 1

a, b = map(int, input().split())
n = int(input())
k = gcd(a, b)
res1, res2 = [], []

i = 1
while i * i <= k:
	if k % i == 0:
		res1.append(i)
		if i != k // i:
			res2.append(k // i)
	i += 1

res1.extend(res2)

for _ in range(n):
	l, r = map(int, input().split())

	print(binary_s(l, r))


# import sys

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

def gcd(num1, num2):
	if num2 == 0:
		return num1

	return gcd(num2, num1 % num2)

# def binary_s(left, right):
# 	while left <= right:
# 		mid = left + (right - left)//2

# 		if res1[mid] > right:
# 			right = mid - 1
# 		else

a, b = map(int, input().split())
n = int(input())
k = gcd(a, b)
res1 = []

i = 1
while i * i <= k:
	if k % i == 0:
		res1.append(i)
		if i != k // i:
			res1.append(k // i)
	i += 1

for _ in range(n):
	l, r = map(int, input().split())
	ans = -1

	for d in res1:
		if l <= d <= r:
			ans = max(ans, d)

	print(ans)


import math
from sys import *
from bisect import bisect_left

input=stdin.readline
print=stdout.write

a,b=map(int,input().split())
n=int(input())

gcd=math.gcd(a,b)
factors=[]
i=1
while(i*i<=gcd):
    if gcd%i==0:
        factors.append(gcd//i)

    if (i*i)!=gcd:
        factors.append(gcd//(gcd//i))

    i+=1

factors.sort()

##print(len(factors))

for _ in range(n):
    l,h=map(int,input().split())
    ans=-1
    index=bisect_left(factors,h,0,len(factors)-1)
##    print(factors,index)
    if factors[index]<=h:
        if index<len(factors) and factors[index]>=l and factors[index]<=h:
            ans=factors[index]

    elif factors[index]>h:
        if index<len(factors) and factors[index-1]>=l and factors[index-1]<=h:
            ans=factors[index-1]

    print(str(ans)+'\n')


import math
a,b=map(int,input().split())
n=int(input())

gcd=math.gcd(a,b)
factors=[]
i=1
while(i*i<=gcd):
    if gcd%i==0:
        factors.append(gcd//i)

    if (i*i)!=gcd:
        factors.append(gcd//(gcd//i))

    i+=1

for _ in range(n):
    l,h=map(int,input().split())
    ans=-1
    for i in factors:
        if i>=l and i<=h:
            ans=max(ans,i)

    print(ans)


import math
from sys import *
input=stdin.readline
print=stdout.write

a,b=map(int,input().split())
n=int(input())

gcd=math.gcd(a,b)
factors=[]
i=1
while(i*i<=gcd):
    if gcd%i==0:
        factors.append(gcd//i)

    if (i*i)!=gcd:
        factors.append(gcd//(gcd//i))

    i+=1

##print(len(factors))

for _ in range(n):
    l,h=map(int,input().split())
    ans=-1
    for i in factors:
        if i>=l and i<=h:
            ans=max(ans,i)

    print(str(ans)+'\n')


import math
from sys import *
from bisect import bisect_right

input=stdin.readline
print=stdout.write

a,b=map(int,input().split())
n=int(input())

gcd=math.gcd(a,b)
##print(gcd)
factors=[]
i=1
while(i*i<=gcd):
    if gcd%i==0:
        factors.append(gcd//i)

        if (i*i)!=gcd:
            factors.append(gcd//(gcd//i))

    i+=1

factors.sort()

for _ in range(n):
    l,h=map(int,input().split())
    ans=-1
    index=bisect_right(factors,h)

    if factors[index-1]>=l and factors[index-1]<=h:
        ans=factors[index-1]

    print(str(ans)+'\n')


import math
r,o=map(int,input().split())
from bisect import *
def fact(x):
    ans=[]
    for  i in range(1,int(math.sqrt(int(x)))+1):
        if(x%i==0):
            if(x//i==i):
                ans.append(i)
            else:
                ans.append(x//i)
                ans.append(i)
    return ans;
m=int(input())
a=math.gcd(r,o)
tem=fact(a)
tem.sort()
for i in range(m):
    x,y=map(int,input().split())
    r=bisect_left(tem,y)
    if(r==len(tem)):
        if(tem[-1]<x):
            print(-1)
        else:
            print(tem[-1])
    else:
        if(tem[r]<=y):
            if(tem[r]<x):
                print(-1)
            else:
                print(tem[r])
        else:
            if(r==0):
                print(-1)
            else:
                if(tem[r-1]<x):
                    print(-1)
                else:
                    print(tem[r-1])


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations
from math import gcd
from bisect import bisect

input = lambda: sys.stdin.readline().rstrip("\r\n")
read = lambda: list(map(int, input().strip().split(" ")))

# sys.setrecursionlimit(10**5)

# def common_divs(a, b):
#     set_a = set(); set_b = set()
#     for i in range(1, int(sqrt(a)+1)):
#         if a % i == 0:
#             set_a.add(i)
#             set_a.add(a//i)
#     for i in range(1, int(sqrt(b)+1)):
#         if b % i == 0:
#             set_b.add(i)
#             set_b.add(b//i)
#     return(list(set_a.intersection(set_b)))

def factors(n):
    arr = set()
    for i in range(1, int(sqrt(n)+1)):
        if n % i == 0:
            arr.add(i)
            arr.add(n//i)
    return(list(arr))

def solve():
    a, b = read()
    # divs = common_divs(a, b)
    divs = factors(gcd(a, b))
    divs.sort()
    # print(divs)
    for _ in range(int(input())):
        l, h = read()
        ind = bisect(divs, h)-1
        if l <= divs[ind]<= h:
            print(divs[ind])
        else:
            print(-1)

if __name__ == "__main__":
	solve()


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations
from math import gcd
from bisect import bisect

input = lambda: sys.stdin.readline().rstrip("\r\n")
read = lambda: list(map(int, input().strip().split(" ")))

# sys.setrecursionlimit(10**5)

def common_divs(a, b):
    set_a = set(); set_b = set()
    for i in range(1, int(sqrt(a)+1)):
        if a % i == 0:
            set_a.add(i)
            set_a.add(a//i)
    for i in range(1, int(sqrt(b)+1)):
        if b % i == 0:
            set_b.add(i)
            set_b.add(b//i)
    return(list(set_a.intersection(set_b)))

def solve():
    a, b = read()
    divs = common_divs(a, b)
    divs.sort()
    # print(divs)
    for _ in range(int(input())):
        l, h = read()
        ind = bisect(divs, h)-1
        if l <= divs[ind]<= h:
            print(divs[ind])
        else:
            print(-1)

if __name__ == "__main__":
	solve()


from math import *
def nwd(a, b):
    while b!=0:
        c = a%b
        a = b
        b = c
    return a

def binSearch(h):
    p = 0
    k = len(dzielniki)-1
    while(p<k):
        s = int((p+k+1)/2)
        if dzielniki[s] > h:
            k = s-1
        else:
            p = s
    return dzielniki[p]

a, b = map(int, input().split())
najwyzszy_dzielnik = nwd(a,b)
dzielniki = []
pierwiastek = int(sqrt(najwyzszy_dzielnik))
#GENEROWANIE WSPOLNYCH DZIELNIKÓW
for i in range(1, pierwiastek+1):
    if najwyzszy_dzielnik%i == 0:
        dzielniki.append(i)
        dzielniki.append(int(najwyzszy_dzielnik/i))
        if i*i == najwyzszy_dzielnik:
            dzielniki.pop()
dzielniki.sort()
t = int(input())
for i in range(t):
    low, high = map(int, input().split())
    wynik = binSearch(high)
    if wynik <= high and wynik >= low:
        print(wynik)
    else:
        print(-1)


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

import math
def main():
    a,b=map(int,input().split(" "))
    gd=math.gcd(a,b)
    temp=[]
    for x in range(1,math.floor(math.sqrt(gd))+1):
        if gd%x==0:
            temp.append(gd//x)
            temp.append(x)
    temp.sort()
    n=int(input())
    for _ in range(n):
        l,r=map(int,input().split(" "))
        ans=-1
        for x in temp:
            if x>=l and x<=r:
                ans=x
        print(ans)

#-----------------------------BOSS-------------------------------------!
# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  if low > dividers[-1]:
    print('-1')
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while dividers[mid] != high:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      print(dividers[mid])
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    else:
      ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  if low > dividers[-1]:
    print('-1')
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while dividers[mid] != high:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    else:
      ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  if dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  if low > dividers[-1]:
    print('-1')
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while dividers[mid] != high:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      print(dividers[mid])
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    else:
      print(dividers[mid])


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[0] == high:
    print(dividers[0])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid-1
    else:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  if low > dividers[-1]:
    print('-1')
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[0] == high:
    print(dividers[0])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid+1
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[0] == high:
    print(dividers[0])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] > high:
      end = mid-1
    else:
      start = mid
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[start]
      break
    #else:
    #  ans = dividers[mid]
  ans = dividers[start]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[0] == high:
    print(dividers[0])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if dividers[0] == high:
    print(dividers[0])
    continue
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid-1
    elif dividers[mid] < high:
      start = mid+1
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


import math
import sys
def gcd(a, b):
  while b>0:
    rest = a%b
    a = b
    b = rest
  return a

dividers = []
(a, b) = tuple(map(int, input().split()))
cases = int(input())
g = math.gcd(a, b)
for x in range(1, int(math.sqrt(g)//1)+1):
  if g%x==0:
    dividers.append(x)
    dividers.append(g//x)
dividers.sort()
dividers = list(dict.fromkeys(dividers))
#print(dividers)
for x in range(cases):
  (low, high) = tuple(map(int, input().split()))
  ans = 0
  if low > dividers[-1] or high < dividers[0]:
    print('-1')
    continue
  elif dividers[-1] <= high and dividers[-1] >=low:
    print(dividers[-1])
    continue
  start = 0
  end = len(dividers)-1
  mid = (start+end+1)//2
  while start<end:
    mid = (start+end+1)//2
    if dividers[mid] <= high and dividers[mid+1] > high:
      ans = dividers[mid]
      break
    if dividers[mid] > high:
      end = mid
    elif dividers[mid] < high:
      start = mid
    #else:
    #  ans = dividers[mid]
  if ans >= low and ans <= high:
    print(ans)
  else:
    print('-1')


#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now-----------------------------------------------------
a,b = list(map(int, input().split()))
cd = math.gcd(a,b)
ar =[]
for i in range(1,int(cd**0.5)+1):
    if cd % i == 0:
        ar.append(i)
        if(i*i != cd):
            ar.append(cd//i)
for _ in range(int(input())):
    l,h = list(map(int, input().split()))
    res = -1
    for i in ar:
        if(i >= l and i <= h):
            res = max(res, i)
    print(res)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
# import numpy as np
# sys.setrecursionlimit(int(pow(10,6)))
# sys.stdout = open("out.txt", "w")
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]

try:
    sys.stdin = open("input.txt", "r")
except:
    pass

# @lru_cache(None)
a,b=L()
sa=set()
sb=set()
sa.add(a)
sb.add(b)
for i in range(2,int(a**0.5)+2):
    if a%i==0:
        sa.add(i)
        sa.add(a//i)
for i in range(2,int(b**0.5)+2):
    if b%i==0:
        sb.add(i)
        sb.add(b//i)
s=sa.intersection(sb)
s.add(1)
s=sorted(list(s))
# print(s)
q=L()[0]
n=len(s)
for i in range(q):
    a,b=L()
    l=bl(s,a)
    r=br(s,b)
    # print(l,r)
    if l>r:
        print(-1)
        continue
    if l==r:
        if l<len(s) and l>=0 and s[l]>=a and s[l]<=b:
            print(s[l])
        else:
            print(-1)
        continue
    while(r>n):
        r-=1
    if l<=r:
        print(s[r-1])
    else:
        print(-1)


import math
n,m=map(int,input().split())
d=math.gcd(n,m)
k=1
l=[]
for i in range(k,int(d**0.5)+1):
    if d%i==0:
        if d//i==i:
            l.append(i)
        else:
            l.append(d//i)
            l.append(i)
l.sort()
for _ in range(int(input())):
    a,b=map(int,input().split())
    m=-1
    for i in l:
        if i>=a and i<=b:
            m=max(i,m)
    print(m)


import math
n,m=map(int,input().split())
d=math.gcd(n,m)
k=1
l=[]
for i in range(k,int(d**0.5)+1):
    if d%i==0:
        if d//i==i:
            l.append(i)
        else:
            l.append(n//i)
            l.append(i)
l.sort()
for _ in range(int(input())):
    a,b=map(int,input().split())
    m=-1
    for i in l:
        if i>=a and i<=b:
            m=max(i,m)
    print(m)


import sys
from array import array  # noqa: F401
from math import gcd
from bisect import bisect_right

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

a, b = map(int, input().split())
g = gcd(a, b)
divisors = [0]
d = 1
while d * d <= g:
    if g % d == 0:
        divisors.append(d)
        if d != g // d:
            divisors.append(g // d)
    d += 1

divisors.sort()

n = int(input())
ans = [-1] * n

for i, (low, high) in enumerate(map(int, input().split()) for _ in range(n)):
    j = bisect_right(divisors, high)
    if low <= divisors[j - 1] <= high:
        ans[i] = divisors[j - 1]

print(*ans, sep='\n')


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(max(n,m)**0.5)+1):
	if n%i == 0 and m%i == 0:
		l.append(i)
		if m%(n//i) == 0:
			l.append(n//i)
#l.sort()
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(min(n,m)**0.5)):
	if n%i == 0 and m%i == 0:
		l.append(i)
		l.append((min(n,m)//i))
if n%(i+1)**2 == 0 and m%(i+1)**2 == 0:
	l.append(i+1)
l.sort()

n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(max(n,m)**0.5)+1):
	if n%i == 0 and m%i == 0:
		l.append(i)
		if m%(n//i) == 0:
			l.append(n//i)
l.sort()
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(n**0.5)+1):
	if n%i == 0 and m%i == 0:
		l.append(i)
	if n%(n//i) == 0 and m%(n//i) == 0:
		l.append(n//i)
l.sort()
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,min(n,m)+1):
	if n%i == 0 and m%i == 0:
		l.append(i)
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(min(n,m)**0.5)):
	if n%i == 0 and m%i == 0:
		l.append(i)
		l.append((min(n,m)//i))
if n%(i+1)**2 == 0 and m%(i+1)**2 == 0:
	l.append(i+1)
l.sort()
l.reverse()
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


n,m = [int(i) for i in input().split()]
l = []
for i in range(1,int(max(n,m)**0.5)+1):
	if n%i == 0 and m%i == 0:
		l.append(i)
		if m%(n//i) == 0:
			l.append(n//i)
#l.sort()
n = int(input())
for i in range(n):
	q,w = [int(j) for j in input().split()]
	mx = -1
	for j in range(len(l)-1,-1,-1):
		if q<=l[j]<=w:
			mx = l[j]
			break
	print(mx)


from bisect import bisect_right as br
from bisect import bisect_left as bl
import math

from functools import reduce

def fac(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

a,b=map(int,input().split())
f1=fac(a)
f2=fac(b)
f=list(f1 & f2)
f=list(set(f))
f.sort()

n=int(input())
for i in range(n):
    l,r=map(int,input().split())
    ans=br(f,r)
    lo=bl(f,l)
    hi=br(f,r)
    if lo==hi:
        print(-1)
    else:
        print(f[ans-1])


from bisect import bisect_right as br
from bisect import bisect_left as bl
import math

def fac(n,f):
    i=1
    while i<=math.sqrt(n):
        if (n%i==0):
            if (n//i==i) :
                f.append(i)
            else :
                f.append(i)
                f.append(n//i)
        i=i+1

a,b=map(int,input().split())
f=[]
fac(a,f)
fac(b,f)
f=list(set(f))
f.sort()

n=int(input())
for i in range(n):
    l,r=map(int,input().split())
    ans=br(f,r)
    x=bl(f,l)
    if f[x]!=l and f[x-1]<l and f[x]>r :
        print(-1)
    else:
        print(f[ans-1])


from bisect import bisect_right as br
from bisect import bisect_left as bl
import math

def fac(n,f):
    i=1
    while i<=math.sqrt(n):
        if (n%i==0):
            if (n//i==i) :
                f.append(i)
            else :
                f.append(i)
                f.append(n//i)
        i=i+1

a,b=map(int,input().split())
f=[]
fac(a,f)
fac(b,f)
f=list(set(f))
f.sort()

n=int(input())
for i in range(n):
    l,r=map(int,input().split())
    ans=br(f,r)
    x=bl(f,l)
    if f[x]!=l and f[x-1]<l:
        print(-1)
    else:
        print(f[ans-1])


from bisect import bisect_right as br
from bisect import bisect_left as bl
import math

from functools import reduce

def fac(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

a,b=map(int,input().split())
f1=fac(a)
f2=fac(b)
f=list(f1 & f2)
f=list(set(f))
f.sort()
print(f)

n=int(input())
for i in range(n):
    l,r=map(int,input().split())
    ans=br(f,r)
    lo=bl(f,l)
    hi=br(f,r)
    if lo==hi:
        print(-1)
    else:
        print(f[ans-1])


"""
Code of Ayush Tiwari
Codeforces: servermonk
Codechef: ayush572000

"""
import sys
import math
from bisect import bisect_right
input = sys.stdin.buffer.readline
def solution():
    n,m=map(int,input().split())
    x=math.gcd(n,m)
    l=[]
    for i in range(1,int(x**0.5)+1):
        if x%i==0:
            if x//i==i:
                l.append(i)
            else:
                l.append(i)
                l.append(x//i)
    l.sort()
    for _ in range(int(input())):
        a,b=map(int,input().split())
        x=bisect_right(l,b)
        if l[x-1]<a:
            print(-1)
        else:
            print(l[x-1])

solution()


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

a,b=value()

for _ in range(Int()):
    low,high=value()

    ans=-1

    while(low<=high):

        mid=low+(high-low)//2

        if(a%mid==0 and b%mid==0):
            ans=mid
            low=mid+1
        else:
            high=mid-1

    print(ans)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

def divisors(n):
    div=set()
    for i in range(1,int(sqrt(n))+1):
        if(n%i==0):
            div.add(i)
            div.add(n//i)
    return div

a,b=value()

div=divisors(a).intersection(divisors(b))
div=sorted(div)

# print(div)

for _ in range(Int()):
    low,high=value()

    ans=bisect_right(div,high)-1

    if(div[ans]>=low):
        ans=div[ans]
    else: ans=-1

    print(ans)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

def divisors(n):
    div=set()
    for i in range(1,int(sqrt(n))+1):
        if(n%i==0):
            div.add(i)
            div.add(n//i)
    return div

a,b=value()

div=divisors(a)
div.intersection(divisors(b))
div=sorted(div)

for _ in range(Int()):
    low,high=value()

    ans=bisect_right(div,high)-1

    if(div[ans]>=low):
        ans=div[ans]
    else: ans=-1

    print(ans)


a, b=map(int, input().split())
n=int(input())
l=[]
i=1
while i-1<a:
    if a%i==0 and b%i==0:
        l.append(i)
        i+=1
    else:
        i+=1
for j in range(n):
    m=[]
    x, y=map(int, input().split())
    for k in range(len(l)):
        if x<=l[k] and y>=l[k]:
            m.append(l[k])
    if len(m)>0:
        print(max(m))
    else:
        print(-1)