Count pairs having distinct sum from a given range
Last Updated :
30 Jun, 2021
Given two positive integers L and R, the task is to find the number of pairs with elements from the range [L, R], whose sums are distinct.
Examples:
Input: L = 2, R = 3
Output: 3
Explanation:
All possible pairs with elements from the range [2, 3] are {(2, 2), (2, 3), (3, 2), (3, 3)}. Since sum of the pairs (2, 3) and (3, 2) are equal, the count of pairs with distinct sum is 3.
Input: L = 2, R = 2
Output: 1
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say firstNum, to store the least sum that can be obtained by the pairs, i.e. 2 * L.
- Initialize a variable, say lastNum, to store the highest sum which can be obtained by the pairs, i.e. 2 * R.
- Initialize a variable, say cntPairs, to store the count of pairs having distinct sum, i.e. lastNum – firstNum + 1.
- Finally, print the value of cntPairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long countPairs( long L, long R)
{
long firstNum = 2 * L;
long lastNum = 2 * R;
long Cntpairs = lastNum - firstNum + 1;
cout << Cntpairs;
}
int main()
{
long L = 2, R = 3;
countPairs(L, R);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void countPairs( long L, long R)
{
long firstNum = 2 * L;
long lastNum = 2 * R;
long Cntpairs = lastNum - firstNum + 1 ;
System.out.println(Cntpairs);
}
public static void main(String[] args)
{
long L = 2 , R = 3 ;
countPairs(L, R);
}
}
|
Python3
def countPairs(L, R):
firstNum = 2 * L
lastNum = 2 * R
Cntpairs = lastNum - firstNum + 1
print (Cntpairs)
if __name__ = = '__main__' :
L,R = 2 , 3
countPairs(L, R)
|
C#
using System;
public class GFG {
static void countPairs( long L, long R)
{
long firstNum = 2 * L;
long lastNum = 2 * R;
long Cntpairs = lastNum - firstNum + 1;
Console.WriteLine(Cntpairs);
}
static public void Main()
{
long L = 2, R = 3;
countPairs(L, R);
}
}
|
Javascript
<script>
function countPairs(L,R)
{
let firstNum = 2 * L;
let lastNum = 2 * R;
let Cntpairs = lastNum - firstNum + 1;
document.write(Cntpairs+ "<br>" );
}
let L = 2, R = 3;
countPairs(L, R);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...