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

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 not` `bool` `isPerfectSquare(vector<``int``>& arr)` `{` `    ``// Map to store the power of prime factors` `    ``map<``int``, ``int``> 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<``int``> 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<``int``, ``int``> freq = ``new` `Dictionary<``int``, ``int``>();`   `        ``// 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)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next