Given three positive integer L, R, G. The task is to find the count of the pair (x,y) having GCD(x,y) = G and x, y lie between L and R.
Input : L = 1, R = 11, G = 5 Output : 3 (5, 5), (5, 10), (10, 5) are three pair having GCD equal to 5 and lie between 1 and 11. So answer is 3. Input : L = 1, R = 10, G = 7 Output : 1
A simple solution is to go through all pairs in [L, R]. For every pair, find its GCD. If GCD is equal to g, then increment count. Finally return count.
An efficient solution is based on the fact that, for any positive integer pair (x, y) to have GCD equal to g, x and y should be divisible by g.
Observe, there will be at most (R – L)/g numbers between L and R which are divisible by g.
So we find numbers between L and R which are divisible by g. For this, we start from ceil(L/g) * g and with increment by g at each step while it doesn’t exceed R, count numbers having GCD equal to 1.
ceil(L/g) * g = floor((L + g - 1) / g) * g.
Below is the implementation of above idea :
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of pairs from the first N natural numbers whose sum is divisible by K
- Count the numbers < N which have equal number of divisors as K
- Divide first N natural numbers into 3 equal sum subsets
- Count pairs from two arrays having sum equal to K
- Count pairs with set bits sum equal to K
- Count natural numbers whose factorials are divisible by x but not y
- Count the pairs in an array such that the difference between them and their indices is equal
- Count of Numbers in Range where first digit is equal to last digit of the number
- Count pairs of numbers from 1 to N with Product divisible by their Sum
- Count ordered pairs of positive numbers such that their sum is S and XOR is K
- Find if given number is sum of first n natural numbers
- Count numbers whose XOR with N is equal to OR with N
- Count numbers whose difference with N is equal to XOR with N
- Sum of first N natural numbers by taking powers of 2 as negative number
- Number of distinct prime factors of first n natural numbers
Improved By : vt_m