All possible co-prime distinct element pairs within a range [L, R]
Given a range [L, R], the task is to find all possible co-prime pairs from the range such that an element doesn’t appear in more than a single pair.
Input : L=1 ; R=6 Output : 3 The answer is 3 [(1, 2) (3, 4) (5, 6)], all these pairs have GCD 1. Input : L=2 ; R=4 Output : 1 The answer is 1 [(2, 3) or (3, 4)] as '3' can only be chosen for a single pair.
Approach: The key observation of the problem is that the numbers with the difference of ‘1’ are always relatively prime to each other i.e. co-primes.
GCD of this pair is always ‘1’. So, the answer will be (R-L+1)/2 [ (total count of numbers in range) / 2 ]
- If R-L+1 is odd then there will be one element left which can not form a pair.
- If R-L+1 is even then all elements can form pairs.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.