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.
Examples:
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:
C++
#include <bits/stdc++.h>
using namespace std;
void CountPair( int L, int R)
{
int x = (R - L + 1);
cout << x / 2 << "\n" ;
}
int main()
{
int L, R;
L = 1, R = 8;
CountPair(L, R);
return 0;
}
|
Java
import java.util.*;
class solution
{
static void CountPair( int L, int R)
{
int x = (R - L + 1 );
System.out.println(x / 2 + "\n" );
}
public static void main(String args[])
{
int L, R;
L = 1 ; R = 8 ;
CountPair(L, R);
}
}
|
Python3
def CountPair(L,R):
x = (R - L + 1 )
print (x / / 2 )
if __name__ = = '__main__' :
L,R = 1 , 8
CountPair(L,R)
|
C#
using System;
class GFG
{
static void CountPair( int L, int R)
{
int x = (R - L + 1);
Console.WriteLine(x / 2 + "\n" );
}
public static void Main()
{
int L, R;
L = 1; R = 8;
CountPair(L, R);
}
}
|
PHP
<?php
function CountPair( $L , $R )
{
$x = ( $R - $L + 1);
echo $x / 2, "\n" ;
}
$L = 1;
$R = 8;
CountPair( $L , $R );
?>
|
Javascript
<script>
function CountPair(L, R)
{
let x = (R - L + 1);
document.write(x / 2 + "<br/>" );
}
let L, R;
L = 1; R = 8;
CountPair(L, R);
</script>
|
Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!