1245. Square Partner Count
A tiling puzzle uses square tiles only, so the product of two numbers matters only when it is a perfect square. You are given an array nums of positive integers. Return, as a long, how many index pairs i < j have nums[i] * nums[j] equal to a perfect square such as 1, 4, 9 or 16.
Equal values at different indices form separate pairs, and the value 1 pairs with every perfect square. Two numbers multiply to a perfect square exactly when the primes that occur an odd number of times in each of them are the same. Use a smallest-prime-factor sieve and a hash map. The intended solution runs in O(M log log M + n log M) time and O(M) space, where M is the largest value in nums and n is its length.
Example 1
- Input:
- nums = [18,50,7,28,63,98,12,27]
- Output:
- 7
- Explanation:
Squares come from 18 with 50 and 98, 50 with 98, 7 with 28 and 63, 28 with 63, and 12 with 27, which is 7 pairs.
Example 2
- Input:
- nums = [10,14,35,40,90,56,22]
- Output:
- 4
- Explanation:
The pairs 10 and 40, 10 and 90, 40 and 90, and 14 and 56 multiply to perfect squares, giving 4.
Example 3
- Input:
- nums = [15,21,35,33,77,55,91]
- Output:
- 0
- Explanation:
Each value has a different set of odd-power primes, so no product is a perfect square and the answer is 0.
Constraints
-
1 ≤ nums.length ≤ 1000 -
1 ≤ nums[i] ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(M log log M + n log M)
- Space
- O(M)