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 <bits/stdc++.h>
using namespace std;
bool isPerfectSquare(vector< int >& arr)
{
map< int , int > freq;
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]++;
}
for ( auto it = freq.begin();
it != freq.end(); it++)
if (it->second % 2)
return false ;
return true ;
}
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 {
public static boolean isPerfectSquare( int [] arr)
{
HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
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 );
}
}
}
for ( int it : freq.values())
if (it % 2 > 0 )
return false ;
return true ;
}
public static void main(String args[]) {
int [] arr = { 1 , 4 , 100 };
if (isPerfectSquare(arr) == true )
System.out.println( "YES" );
else
System.out.println( "NO" );
}
}
|
Python3
import math
def isPerfectSquare(arr):
freq = dict ()
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
for value in freq.values():
if (value % 2 = = 1 ):
return False
return True
arr = [ 1 , 4 , 100 ]
print ( "YES" ) if isPerfectSquare(arr) else print ( "NO" )
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static bool isPerfectSquare( int [] arr)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
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);
}
}
}
foreach ( int it in freq.Values)
if (it % 2 > 0)
return false ;
return true ;
}
public static void Main(String []args) {
int [] arr = { 1, 4, 100 };
if (isPerfectSquare(arr) == true )
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
}
|
Javascript
<script>
function isPerfectSquare(arr)
{
let freq = new Map();
for (let x of arr) {
for (let i = 2; i <= Math.floor(Math.sqrt(x)); i++) {
while (x > 1 && x % i == 0) {
if (freq.has(i))
freq.set(i, freq.get(i) + 1);
else
freq.set(i, 1);
x = Math.floor(x / i);
}
}
if (x >= 2)
freq.set(x, freq.get(x) + 1)
}
for (let value of freq.values()) {
if (value % 2 == 1)
return false ;
}
return true ;
}
let arr = [1, 4, 100];
isPerfectSquare(arr)
? document.write( "YES" + '<br>' )
: document.write( "NO" + '<br>' );
</script>
|
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!
Last Updated :
17 Dec, 2021
Like Article
Save Article