📌  相关文章
📜  乘积是一个完美平方的数组中的对数

📅  最后修改于: 2021-04-29 14:50:11             🧑  作者: Mango

给定N个整数的数组arr [] ,任务是找到对数(arr [i],arr [j]) ,以使arr [i] * arr [j]是一个完美的平方。

例子:

天真的方法:
1到n运行两个循环,并计算所有对(i,j) ,其中arr [i] * arr [j]是一个理想平方。该方法的时间复杂度将为O(N 2 )

高效方法:
arr []中的每个整数都可以用以下形式表示:

arr[i] = k*x          ..............(1)
where k is not divisible by any perfect square other than 1,
and x = perfect square,

脚步:

  1. 以等式(1)的形式表示每个元素。
  2. 然后,对于每对(ARR [I],编曲[j]的)ARR []可表示为:
    arr[i] = ki*x;
    arr[j] = kj*y;
    where x and y are perfect square
    

    对于对(arr [i],arr [j]) ,当且仅当k i = k j时arr [i]arr [j]的乘积可以是理想平方。

  3. 使用Eratosthenes筛子为数组arr []中的每个元素预先计算k的值。
  4. 将每个元素的k频率存储在map的arr []中。
  5. 因此,对的总数由频率大于1的元素形成的对的数目给定。
  6. 由n个元素构成的对的总数由下式给出:
    Number of Pairs = (f*(f-1))/2
    where f is the frequency of an element.
    

下面是上述方法的实现:

C++
// C++ program to calculate the number of
// pairs with product is perfect square
#include 
using namespace std;
  
// Prime[] array to calculate Prime Number
int prime[100001] = { 0 };
  
// Array k[] to store the value of k for
// each element in arr[]
int k[100001] = { 0 };
  
// For value of k, Sieve function is
// implemented
void Sieve()
{
    // Initialize k[i] to i
    for (int i = 1; i < 100001; i++)
        k[i] = i;
  
    // Prime Sieve
    for (int i = 2; i < 100001; i++) {
  
        // If i is prime then remove all
        // factors of prime from it
        if (prime[i] == 0)
            for (int j = i; j < 100001; j += i) {
  
                // Update that j is not
                // prime
                prime[j] = 1;
  
                // Remove all square divisors
                // i.e. if k[j] is divisible
                // by i*i then divide it by i*i
                while (k[j] % (i * i) == 0)
                    k[j] /= (i * i);
            }
    }
}
  
// Function that return total count
// of pairs with pefect square product
int countPairs(int arr[], int n)
{
    // Map used to store the frequency of k
    unordered_map freq;
  
    // Store the frequency of k
    for (int i = 0; i < n; i++) {
        freq[k[arr[i]]]++;
    }
  
    int sum = 0;
  
    // The total number of pairs is the
    // summation of (fi * (fi - 1))/2
    for (auto i : freq) {
        sum += ((i.second - 1) * i.second) / 2;
    }
  
    return sum;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 4, 8, 5, 6 };
  
    // Size of arr[]
    int n = sizeof(arr) / sizeof(int);
  
    // To pre-compute the value of k
    Sieve();
  
    // Function that return total count
    // of pairs with perfect square product
    cout << countPairs(arr, n) << endl;
  
    return 0;
}


Java
// Java program to calculate the number of
// pairs with product is perfect square
import java.util.*;
  
class GFG{
   
// Prime[] array to calculate Prime Number
static int []prime = new int[100001];
   
// Array k[] to store the value of k for
// each element in arr[]
static int []k = new int[100001];
   
// For value of k, Sieve function is
// implemented
static void Sieve()
{
    // Initialize k[i] to i
    for (int i = 1; i < 100001; i++)
        k[i] = i;
   
    // Prime Sieve
    for (int i = 2; i < 100001; i++) {
   
        // If i is prime then remove all
        // factors of prime from it
        if (prime[i] == 0)
            for (int j = i; j < 100001; j += i) {
   
                // Update that j is not
                // prime
                prime[j] = 1;
   
                // Remove all square divisors
                // i.e. if k[j] is divisible
                // by i*i then divide it by i*i
                while (k[j] % (i * i) == 0)
                    k[j] /= (i * i);
            }
    }
}
   
// Function that return total count
// of pairs with pefect square product
static int countPairs(int arr[], int n)
{
    // Map used to store the frequency of k
    HashMap freq = new HashMap();
   
    // Store the frequency of k
    for (int i = 0; i < n; i++) {
        if(freq.containsKey(k[arr[i]])) {
            freq.put(k[arr[i]], freq.get(k[arr[i]])+1);
        }
        else
            freq.put(k[arr[i]], 1);
    }
   
    int sum = 0;
   
    // The total number of pairs is the
    // summation of (fi * (fi - 1))/2
    for (Map.Entry i : freq.entrySet()){
        sum += ((i.getValue() - 1) * i.getValue()) / 2;
    }
   
    return sum;
}
   
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 4, 8, 5, 6 };
   
    // Size of arr[]
    int n = arr.length;
   
    // To pre-compute the value of k
    Sieve();
   
    // Function that return total count
    // of pairs with perfect square product
    System.out.print(countPairs(arr, n) +"\n");
   
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to calculate the number  
# of pairs with product is perfect square
  
# prime[] array to calculate Prime Number
prime = [0] * 100001
  
# Array to store the value of k 
# for each element in arr[]
k = [0] * 100001
  
# For value of k, Sieve implemented
def Sieve():
  
    # Initialize k[i] to i
    for i in range(1, 100001):
        k[i] = i
  
    # Prime sieve
    for i in range(2, 100001):
  
        # If i is prime then remove all
        # factors of prime from it
        if (prime[i] == 0):
            for j in range(i, 100001, i):
  
                # Update that j is not prime
                prime[j] = 1
  
                # Remove all square divisors 
                # i.e if k[j] is divisible by
                # i*i then divide it by i*i
                while (k[j] % (i * i) == 0):
                    k[j] /= (i * i)
  
# Function that return total count of
# pairs with perfect square product
def countPairs (arr, n):
  
    # Store the frequency of k
    freq = dict()
  
    for i in range(n):
        if k[arr[i]] in freq.keys():
            freq[k[arr[i]]] += 1
        else:
            freq[k[arr[i]]] = 1
  
    Sum = 0
  
    # The total number of pairs is the 
    # summation of (fi * (fi - 1))/2
    for i in freq:
        Sum += (freq[i] * (freq[i] - 1)) / 2
  
    return Sum
  
# Driver code 
arr = [ 1, 2, 4, 8, 5, 6 ]
  
# Length of arr
n = len(arr) 
  
# To pre-compute the value of k
Sieve()
  
# Function that return total count 
# of pairs with perfect square product 
print(int(countPairs(arr, n)))
  
# This code is contributed by himanshu77


C#
// C# program to calculate the number of
// pairs with product is perfect square
using System;
using System.Collections.Generic;
  
class GFG{
    
// Prime[] array to calculate Prime Number
static int []prime = new int[100001];
    
// Array k[] to store the value of k for
// each element in []arr
static int []k = new int[100001];
    
// For value of k, Sieve function is
// implemented
static void Sieve()
{
    // Initialize k[i] to i
    for (int i = 1; i < 100001; i++)
        k[i] = i;
    
    // Prime Sieve
    for (int i = 2; i < 100001; i++) {
    
        // If i is prime then remove all
        // factors of prime from it
        if (prime[i] == 0)
            for (int j = i; j < 100001; j += i) {
    
                // Update that j is not
                // prime
                prime[j] = 1;
    
                // Remove all square divisors
                // i.e. if k[j] is divisible
                // by i*i then divide it by i*i
                while (k[j] % (i * i) == 0)
                    k[j] /= (i * i);
            }
    }
}
    
// Function that return total count
// of pairs with pefect square product
static int countPairs(int []arr, int n)
{
    // Map used to store the frequency of k
    Dictionary freq = new Dictionary();
    
    // Store the frequency of k
    for (int i = 0; i < n; i++) {
        if(freq.ContainsKey(k[arr[i]])) {
            freq[k[arr[i]]] = freq[k[arr[i]]]+1;
        }
        else
            freq.Add(k[arr[i]], 1);
    }
    
    int sum = 0;
    
    // The total number of pairs is the
    // summation of (fi * (fi - 1))/2
    foreach (KeyValuePair i in freq){
        sum += ((i.Value - 1) * i.Value) / 2;
    }
    
    return sum;
}
    
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 4, 8, 5, 6 };
    
    // Size of []arr
    int n = arr.Length;
    
    // To pre-compute the value of k
    Sieve();
    
    // Function that return total count
    // of pairs with perfect square product
    Console.Write(countPairs(arr, n) +"\n");  
}
}
  
// This code is contributed by PrinciRaj1992


输出:
2

时间复杂度: O(N * log(log N))