Check if the Product of all Array elements is a Perfect Square or not

• Last Updated : 17 Dec, 2021

Given an array arr[] consisting of N positive integers, the task is to check if the product of all the elements of the given array arr[] is a perfect square or not. If found to be true, then print Yes. Otherwise, print No.

Examples:

Input: arr[] = {1, 4, 100}
Output: Yes
Explanation: The product of all the numbers is 1 x 4 x 100 = 400 which is a perfect square. Therefore, print “Yes”.

Input: arr[] = {1, 3}
Output: No

Naive Approach: Find the product of all the elements of the array and try to find if this is a perfect square or not. But the problem with this approach is that the product can be so large that we cannot store it and hence this approach will fail.
Time Complexity: O(N)
Auxiliary Space: O(1)

Efficient Approach: This approach is based on mathematical observation. A number is a perfect square if all the prime factors of the number are raised to powers that are even. We will be using this concept to find if the product is a perfect square or not. Follow the steps mentioned below:

• Create a frequency array to store the powers of prime factors.
• Start traversing the array.
• For each element arr[i] use Sieve of Eratosthenes to find the powers of the prime factors of arr[i] and add that in the frequency array.
• After array is traversed, start traversing the frequency array.
• If any element (except 1) has odd frequency then return false, otherwise, return true.

Below is the implementation of the above approach:

C++

 #include using namespace std; // Function to check if the product// of all elements is perfect square or notbool 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 codeint 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 approachimport math # Function to check if the product# of all elements is perfect square or notdef 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 codearr = [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


Output
YES

Time Complexity: O(N * log X) where X is the largest element of the array
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up