📌  相关文章
📜  检查所有 Array 元素的 Product 是否为 Perfect Square

📅  最后修改于: 2022-05-13 01:56:04.757000             🧑  作者: Mango

检查所有 Array 元素的 Product 是否为 Perfect Square

给定一个由N个正整数组成的数组arr[] ,任务是检查给定数组 arr[]的所有元素的乘积是否是完全平方。如果发现是真的,则打印 Yes。否则,打印编号。

例子:

朴素方法:找到数组所有元素的乘积,并尝试找出这是否是一个完美的正方形。但是这种方法的问题是产品可能太大以至于我们无法存储它,因此这种方法会失败
时间复杂度: O(N)
辅助空间: O(1)

有效方法:这种方法基于数学观察。如果一个数的所有质因数都提高到偶数次方,则该数是一个完全平方。我们将使用这个概念来确定产品是否是完美的正方形。请按照以下步骤操作:

  • 创建一个频率数组来存储素因数的幂。
  • 开始遍历数组。
  • 对于每个元素arr[i] ,使用埃拉托色尼筛法找出 arr[i] 的素因子,并将其添加到频率数组中。
  • 遍历数组后,开始遍历频率数组
  • 如果任何元素(除了 1)具有奇数频率,则返回false ,否则返回 true。

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to check if the product
// of all elements is perfect square or not
bool isPerfectSquare(vector& arr)
{
    // Map to store the power of prime factors
    map freq;
 
    // Loop to implement the concept
    // of Sieve of Eratosthenes
    for (int x : arr) {
        for (int i = 2; i <= sqrt(x); i++) {
            while (x > 1 and x % i == 0) {
                freq[i]++;
                x /= i;
            }
        }
        if (x >= 2)
            freq[x]++;
    }
 
    // Loop to check if all the prime factors
    // have even power
    for (auto it = freq.begin();
         it != freq.end(); it++)
        if (it->second % 2)
            return false;
 
    return true;
}
 
// Driver code
int main()
{
    vector arr = { 1, 4, 100 };
 
    isPerfectSquare(arr)
        ? cout << "YES\n"
        : cout << "NO\n";
    return 0;
}


Java
import java.util.HashMap;
 
class GFG {
 
    // Function to check if the product
    // of all elements is perfect square or not
    public static boolean isPerfectSquare(int[] arr)
    {
       
        // Map to store the power of prime factors
        HashMap freq = new HashMap();
 
        // Loop to implement the concept
        // of Sieve of Eratosthenes
        for (int x : arr) {
            for (int i = 2; i <= Math.sqrt(x); i++) {
                while (x > 1 && x % i == 0) {
                    if (freq.containsKey(i)) {
                        freq.put(i, freq.get(i) + 1);
                    } else {
                        freq.put(i, 1);
                    }
                    x /= i;
                }
            }
            if (x >= 2) {
                if (freq.containsKey(x)) {
                    freq.put(x, freq.get(x) + 1);
                } else {
                    freq.put(x, 1);
                }
            }
        }
 
        // Loop to check if all the prime factors
        // have even power
        for (int it : freq.values())
            if (it % 2 > 0)
                return false;
 
        return true;
    }
 
    // Driver code
    public static void main(String args[]) {
        int[] arr = { 1, 4, 100 };
 
        if (isPerfectSquare(arr) == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}
 
// This code is contributed by gfgking.


Python3
# Python Program to implement
# the above approach
import math
 
# Function to check if the product
# of all elements is perfect square or not
def isPerfectSquare(arr):
 
    # Map to store the power of prime factors
    freq = dict()
 
    # Loop to implement the concept
    # of Sieve of Eratosthenes
    for x in arr:
        for i in range(2, math.floor(math.sqrt(x)) + 1):
            while (x > 1 and x % i == 0):
                if (i in freq):
                    freq[i] += + 1
                else:
                    freq[i] = 1
 
                x = x // i
        if (x >= 2):
            freq[x] += 1
     
    # Loop to check if all the prime factors
    # have even power
    for value in freq.values():
        if (value % 2 == 1):
            return False
    return True
 
# Driver code
arr = [1, 4, 100]
print("YES") if isPerfectSquare(arr) else print("NO")
 
# This code is contributed by gfgking


C#
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to check if the product
    // of all elements is perfect square or not
    public static bool isPerfectSquare(int[] arr)
    {
       
        // Map to store the power of prime factors
        Dictionary freq = new Dictionary();
 
        // Loop to implement the concept
        // of Sieve of Eratosthenes
        int new_x = 0;
        foreach (int x in arr) {
            new_x = x;
            for (int i = 2; i <= Math.Sqrt(new_x); i++) {
                while (new_x > 1 && x % i == 0) {
                    if (freq.ContainsKey(i)) {
                        freq[i] = freq[i] + 1;
                    } else {
                        freq.Add(i, 1);
                    }
                    new_x = new_x/i;
                }
            }
            if (new_x >= 2) {
                if (freq.ContainsKey(new_x)) {
                    freq[new_x] = freq[new_x] + 1;
                } else {
                    freq.Add(new_x, 1);
                }
            }
        }
 
        // Loop to check if all the prime factors
        // have even power
        foreach (int it in freq.Values)
            if (it % 2 > 0)
                return false;
 
        return true;
    }
 
    // Driver code
    public static void Main(String []args) {
        int[] arr = { 1, 4, 100 };
 
        if (isPerfectSquare(arr) == true)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
YES

时间复杂度: O(N * log X) 其中 X 是数组的最大元素
辅助空间: O(N)