Greatest Common Divisor in a Range

You are given two positive integers a and b.

For each query [low, high], find the largest integer d such that:

  • d divides both a and b
  • low <= d <= high

If there is no common divisor of a and b in that range, return -1 for that query.

Return an array where the ith element is the answer to the ith query.

Example 1:

Input: a = 12, b = 18, queries = [[1, 3], [4, 6], [7, 10]]

Output: [3, 6, -1]

Explanation:

The common divisors of 12 and 18 are: 1, 2, 3, 6

  • For query [1, 3], the divisors in range are 1, 2, 3, so the answer is 3
  • For query [4, 6], the only valid divisor is 6, so the answer is 6
  • For query [7, 10], there is no common divisor in the range, so the answer is -1

Example 2:

Input: a = 100, b = 80, queries = [[1, 5], [6, 10], [11, 25]]

Output: [5, 10, 20]

Explanation:

The common divisors of 100 and 80 are: 1, 2, 4, 5, 10, 20

  • For query [1, 5], the largest valid divisor is 5
  • For query [6, 10], the largest valid divisor is 10
  • For query [11, 25], the largest valid divisor is 20

Now Your Turn!

Pick the correct output for the given input

Input: a = 30, b = 45, queries = [[2, 8]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= a, b <= 109
  • 1 <= queries.length <= 104
  • 1 <= low <= high <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<int> gcdInRange(int a, int b, vector<vector<int>> &queries) {
// Your code goes here
}
};
 
Test Case

Input:

A
B
Queries