📜  给定数组中每对绝对差的乘积

📅  最后修改于: 2021-05-17 22:18:14             🧑  作者: Mango

给定一个由N个元素组成的数组arr [] ,任务是查找给定数组中所有对的绝对差的乘积。

例子:

方法:想法是生成给定数组arr []的每个可能的对,并找到所有对的绝对差的乘积。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to return the product of
// abs diff of all pairs (x, y)
int getProduct(int a[], int n)
{
    // To store product
    int p = 1;
 
    // Iterate all possible pairs
    for (int i = 0; i < n; i++) {
 
        for (int j = i + 1; j < n; j++) {
 
            // Find the product
            p *= abs(a[i] - a[j]);
        }
    }
 
    // Return product
    return p;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << getProduct(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to return the product of
// abs diff of all pairs (x, y)
static int getProduct(int a[], int n)
{
     
    // To store product
    int p = 1;
 
    // Iterate all possible pairs
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
 
            // Find the product
            p *= Math.abs(a[i] - a[j]);
        }
    }
 
    // Return product
    return p;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4 };
    int N = arr.length;
 
    // Function call
    System.out.println(getProduct(arr, N));
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 program for
# the above approach
 
# Function to return the product of
# abs diff of all pairs (x, y)
def getProduct(a, n):
 
    # To store product
    p = 1
     
    # Iterate all possible pairs
    for i in range (n):
        for j in range (i + 1, n):
           
            # Find the product
            p *= abs(a[i] - a[j])
             
    # Return product
    return p
   
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [1, 2, 3, 4]
    N = len(arr)
     
    # Function Call
    print (getProduct(arr, N))
   
# This code is contributed by Chitranayal


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to return the product of
// abs diff of all pairs (x, y)
static int getProduct(int []a, int n)
{
     
    // To store product
    int p = 1;
 
    // Iterate all possible pairs
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
 
            // Find the product
            p *= Math.Abs(a[i] - a[j]);
        }
    }
 
    // Return product
    return p;
}
 
// Driver Code
public static void Main(string[] args)
{
     
    // Given array arr[]
    int []arr = { 1, 2, 3, 4 };
    int N = arr.Length;
 
    // Function call
    Console.Write(getProduct(arr, N));
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
12

时间复杂度: O(N 2 )
辅助空间: O(1)