给定四个整数a , b , c和d 。任务是检查是否有可能将它们配对以使它们成比例。我们被允许随机排列数字的顺序。
例子:
Input: arr[] = {1, 2, 4, 2}
Output: Yes
1 / 2 = 2 / 4
Input: arr[] = {1, 2, 5, 2}
Output: No
方法:如果四个数字a,b,c和d成比例,则a:b = c:d 。解决方案是对四个数字进行排序,然后将前两个数字和最后两个数字配对,并检查它们的比率,这是因为,为了使它们成比例,均值的乘积必须等于极值的乘积。因此, a * d必须等于c * b 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if the
// given four integers are in proportion
bool inProportion(int arr[])
{
// Array will consist of
// only four integers
int n = 4;
// Sort the array
sort(arr, arr + n);
// Find the product of extremes and means
long extremes = (long)arr[0] * (long)arr[3];
long means = (long)arr[1] * (long)arr[2];
// If the products are equal
if (extremes == means)
return true;
return false;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4, 2 };
if (inProportion(arr))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function that returns true if the
// given four integers are in proportion
static boolean inProportion(int []arr)
{
// Array will consist of
// only four integers
int n = 4;
// Sort the array
Arrays.sort(arr);
// Find the product of extremes and means
long extremes = (long)arr[0] * (long)arr[3];
long means = (long)arr[1] * (long)arr[2];
// If the products are equal
if (extremes == means)
return true;
return false;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 2, 4, 2 };
if (inProportion(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation of the approach
# Function that returns true if the
# given four integers are in proportion
def inProportion(arr) :
# Array will consist of
# only four integers
n = 4;
# Sort the array
arr.sort()
# Find the product of extremes and means
extremes = arr[0] * arr[3];
means = arr[1] * arr[2];
# If the products are equal
if (extremes == means) :
return True;
return False;
# Driver code
if __name__ == "__main__" :
arr = [ 1, 2, 4, 2 ];
if (inProportion(arr)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if the
// given four integers are in proportion
static bool inProportion(int []arr)
{
// Array will consist of
// only four integers
int n = 4;
// Sort the array
Array.Sort(arr);
// Find the product of extremes and means
long extremes = (long)arr[0] * (long)arr[3];
long means = (long)arr[1] * (long)arr[2];
// If the products are equal
if (extremes == means)
return true;
return false;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 1, 2, 4, 2 };
if (inProportion(arr))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Princi Singh
Javascript
输出:
Yes
时间复杂度: O(1)