Check whether the given integers a, b, c and d are in proportion
Given four integers a, b, c and d. The task is to check whether it is possible to pair them up such that they are in proportion. We are allowed to shuffle the order of the numbers.
Examples:
Input: arr[] = {1, 2, 4, 2}
Output: Yes
1 / 2 = 2 / 4
Input: arr[] = {1, 2, 5, 2}
Output: No
Approach: If four numbers a, b, c and d are in proportion then a:b = c:d. The solution is to sort the four numbers and pair up the first 2 together and the last 2 together and check their ratios this is because, in order for them to be in proportion, the product of means has to be equal to the product of extremes. So, a * d has to be equal to c * b.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool inProportion( int arr[])
{
int n = 4;
sort(arr, arr + n);
long extremes = ( long )arr[0] * ( long )arr[3];
long means = ( long )arr[1] * ( long )arr[2];
if (extremes == means)
return true ;
return false ;
}
int main()
{
int arr[] = { 1, 2, 4, 2 };
if (inProportion(arr))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean inProportion( int []arr)
{
int n = 4 ;
Arrays.sort(arr);
long extremes = ( long )arr[ 0 ] * ( long )arr[ 3 ];
long means = ( long )arr[ 1 ] * ( long )arr[ 2 ];
if (extremes == means)
return true ;
return false ;
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 4 , 2 };
if (inProportion(arr))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def inProportion(arr) :
n = 4 ;
arr.sort()
extremes = arr[ 0 ] * arr[ 3 ];
means = arr[ 1 ] * arr[ 2 ];
if (extremes = = means) :
return True ;
return False ;
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 2 ];
if (inProportion(arr)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static bool inProportion( int []arr)
{
int n = 4;
Array.Sort(arr);
long extremes = ( long )arr[0] * ( long )arr[3];
long means = ( long )arr[1] * ( long )arr[2];
if (extremes == means)
return true ;
return false ;
}
public static void Main(String []args)
{
int []arr = { 1, 2, 4, 2 };
if (inProportion(arr))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function inProportion(arr)
{
var n = 4;
arr.sort();
var extremes = arr[0] * arr[3];
var means = arr[1] * arr[2];
if (extremes == means)
return true ;
return false ;
}
var arr = [ 1, 2, 4, 2 ]
if (inProportion(arr))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n * log n)
Last Updated :
10 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...