Count pairs of natural numbers with GCD equal to given number - GeeksforGeeks
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.
Read full article from Count pairs of natural numbers with GCD equal to given number - GeeksforGeeks
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.
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.
Also,
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.
Also,
ceil(L/g) * g = floor((L + g - 1) / g) * g.
int
gcd(
int
a,
int
b)
{
return
b ? gcd(b, a % b) : a;
}
// Return the count of pairs having GCD equal to g.
int
countGCD(
int
L,
int
R,
int
g)
{
// Setting the value of L, R.
L = (L + g - 1) / g;
R = R/ g;
// For each possible pair check if GCD is 1.
int
ans = 0;
for
(
int
i = L; i <= R; i++)
for
(
int
j = L; j <= R; j++)
if
(gcd(i, j) == 1)
ans++;
return
ans;
}