Check if product of array containing prime numbers is a perfect square in Python

Suppose we have an array nums with all prime numbers. We have to check whether the product of all numbers present in nums is a perfect square or not.

A perfect square is formed when every prime factor appears an even number of times. Since our array contains only prime numbers, we need to count the frequency of each prime and ensure all frequencies are even.

So, if the input is like nums = [3,3,7,7], then the output will be True as product of all elements in nums is 441 which is a perfect square as 21² = 441.

Algorithm

To solve this, we will follow these steps ?

  • Create a frequency map of all elements in nums
  • For each unique prime in the array, check if its frequency is odd
  • If any prime has odd frequency, return False
  • If all primes have even frequencies, return True

Example

Let us see the following implementation to get better understanding ?

from collections import defaultdict

def solve(nums):
    # Count frequency of each prime number
    m = defaultdict(int)
    for key in nums:
        m[key] += 1
    
    # Check if any prime has odd frequency
    for key in m:
        if m[key] % 2 == 1:
            return False
    
    return True

nums = [3, 3, 7, 7]
print(solve(nums))

The output of the above code is ?

True

Alternative Approach Using Counter

We can also use Python's Counter class for cleaner code ?

from collections import Counter

def is_perfect_square_product(nums):
    # Count frequencies using Counter
    freq = Counter(nums)
    
    # Check if all frequencies are even
    return all(count % 2 == 0 for count in freq.values())

nums = [3, 3, 7, 7]
print(is_perfect_square_product(nums))

# Test with odd frequencies
nums2 = [2, 3, 3, 5]
print(is_perfect_square_product(nums2))

The output of the above code is ?

True
False

How It Works

The algorithm works because a number is a perfect square if and only if every prime in its prime factorization appears an even number of times. Since our input array contains only primes, the product will be a perfect square when each prime appears an even number of times in the array.

Conclusion

To check if the product of prime numbers is a perfect square, count the frequency of each prime and verify all frequencies are even. Use Counter for cleaner implementation or defaultdict for basic frequency counting.

Updated on: 2026-03-25T15:22:04+05:30

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements