Given a range, we need to check if is their any pairs in the segment whose GCD is divisible by k.
Input : l=4, r=6, k=2 Output : YES There are two numbers 4 and 6 whose GCD is 2 which is divisible by 2. Input : l=3 r=5 k=4 Output : NO Their is no such pair whose gcd is divisible by 5.
Basically we need to count such numbers in range l to r such that they are divisible by k. Because if we choose any such two numbers then their gcd is also a multiple of k. Now if count of such numbers is greater than one then we can form pair, otherwise it’s impossible to form a pair (x, y) such that gcd(x, y) is divisible by k.
Below is the implementation of above approach:
// function to count such
// possible numbers
public bool Check_is_possible(int l, int r,
int count = 0;
for (int i = l; i <= r; i++)
// if i is divisible by k
if (i % k == 0)
// if count of such numbers
// is greater than one
return (count > 1);
// Driver code
public static void Main()
GFG g = new GFG();
int l = 4, r = 12;
int k = 5;
if (g.Check_is_possible(l, r, k))
// This code is contributed
// by Soumik
Time Complexity: O(r – l + 1)
An efficient solution is based on the efficient approach discussed here.
- Subset with no pair sum divisible by K
- Subarray with no pair sum divisible by K
- Triplet pair (a, b, c) such that a+b, b+c and a+c are all divisible by K
- Maximum XOR value of a pair from a range
- Minimum pair sum operations to make array each element divisible by 4
- Sum of all numbers divisible by 6 in a given range
- Count the numbers divisible by 'M' in a given range
- No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x
- Queries to find maximum product pair in range with updates
- Count numbers in range L-R that are divisible by all of its non-zero digits
- Sum of largest divisible powers of p (a prime number) in a range
- Check for Amicable Pair
- Check if the given two numbers are friendly pair or not
- Given an array A and a number x, check for pair in A with sum as x
- Check if product of every pair exists in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SoumikMondal