给定数组arr [] ,任务是查找数组中的对数(arr [i],arr [j]) ,以使arr [i] + arr [j] = arr [i] * arr [j ]
例子:
Input: arr[] = {2, 2, 3, 4, 6}
Output: 1
(2, 2) is the only possible pair as (2 + 2) = (2 * 2) = 4.
Input: arr[] = {1, 2, 3, 4, 5}
Output: 0
方法:满足给定条件的唯一可能的整数对是(0,0)和(2,2) 。因此,现在的任务是计算数组中0和2的数量,并将它们分别存储在cnt0和cnt2中,然后所需的计数将是(cnt0 *(cnt0 – 1))/ 2 +(cnt2 *(cnt2 – 1) ))/ 2 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of the required pairs
int sumEqualProduct(int a[], int n)
{
int zero = 0, two = 0;
// Find the count of 0s
// and 2s in the array
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
zero++;
}
if (a[i] == 2) {
two++;
}
}
// Find the count of required pairs
int cnt = (zero * (zero - 1)) / 2
+ (two * (two - 1)) / 2;
// Return the count
return cnt;
}
// Driver code
int main()
{
int a[] = { 2, 2, 3, 4, 2, 6 };
int n = sizeof(a) / sizeof(a[0]);
cout << sumEqualProduct(a, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG {
// Function to return the count
// of the required pairs
static int sumEqualProduct(int a[], int n)
{
int zero = 0, two = 0;
// Find the count of 0s
// and 2s in the array
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
zero++;
}
if (a[i] == 2) {
two++;
}
}
// Find the count of required pairs
int cnt = (zero * (zero - 1)) / 2
+ (two * (two - 1)) / 2;
// Return the count
return cnt;
}
// Driver code
public static void main(String[] args)
{
int a[] = { 2, 2, 3, 4, 2, 6 };
int n = a.length;
System.out.print(sumEqualProduct(a, n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python 3 implementation of the approach
# Function to return the count
# of the required pairs
def sumEqualProduct(a, n):
zero = 0
two = 0
# Find the count of 0s
# and 2s in the array
for i in range(n):
if a[i] == 0:
zero += 1
if a[i] == 2:
two += 1
# Find the count of required pairs
cnt = (zero * (zero - 1)) // 2 + \
(two * (two - 1)) // 2
# Return the count
return cnt
# Driver code
a = [ 2, 2, 3, 4, 2, 6 ]
n = len(a)
print(sumEqualProduct(a, n))
# This code is contributed by Ankit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count
// of the required pairs
static int sumEqualProduct(int []a, int n)
{
int zero = 0, two = 0;
// Find the count of 0s
// and 2s in the array
for (int i = 0; i < n; i++)
{
if (a[i] == 0)
{
zero++;
}
if (a[i] == 2)
{
two++;
}
}
// Find the count of required pairs
int cnt = (zero * (zero - 1)) / 2 +
(two * (two - 1)) / 2;
// Return the count
return cnt;
}
// Driver code
public static void Main(String[] args)
{
int []a = { 2, 2, 3, 4, 2, 6 };
int n = a.Length;
Console.Write(sumEqualProduct(a, n));
}
}
// This code is contributed by 29AjayKumar
输出:
3
时间复杂度: O(N)
辅助空间: O(1)