Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
All possible co-prime distinct element pairs within a range [L, R]?
Here we will see how to count the number of co-prime pairs from a given range, where each number appears in at most one pair.
Before discussing the logic, let us understand what co-prime numbers are. Co-prime numbers are two numbers that have no common positive divisors other than 1. In other words, the GCD (Greatest Common Divisor) of these two numbers is 1.
For example, if the lower and upper limits are 1 and 6, then there are three possible pairs: (1, 2), (3, 4), and (5, 6). Each of these pairs consists of consecutive numbers, which are always co-prime.
The key insight is that consecutive integers are always co-prime. Therefore, we can pair consecutive numbers from the range [L, R]. The total count will be (R − L + 1)/2. If (R − L + 1) is odd, one number will be left unpaired.
Syntax
int countCoPrimePairs(int L, int R);
Algorithm
countCoPrimePairs(L, R)
Begin return (R - L + 1)/2 End
Example
The following program demonstrates how to count co-prime pairs in a given range −
#include <stdio.h>
int countCoPrimePairs(int L, int R) {
return (R - L + 1) / 2;
}
int main() {
int l = 1, r = 6;
printf("Range: [%d, %d]
", l, r);
printf("Numbers in range: ");
for(int i = l; i <= r; i++) {
printf("%d ", i);
}
printf("\nPossible pairs: (1,2), (3,4), (5,6)
");
printf("Number of co-prime pairs: %d
", countCoPrimePairs(l, r));
return 0;
}
Output
Range: [1, 6] Numbers in range: 1 2 3 4 5 6 Possible pairs: (1,2), (3,4), (5,6) Number of co-prime pairs: 3
How It Works
- Consecutive integers are always co-prime because GCD(n, n+1) = 1 for any integer n.
- We form pairs (L, L+1), (L+2, L+3), ... until we reach R.
- The formula (R − L + 1)/2 gives us the maximum number of such pairs.
Conclusion
Finding co-prime pairs in a range is simplified by using consecutive numbers, which are always co-prime. The solution has O(1) time complexity using the direct formula (R − L + 1)/2.
