You are given two lists and you have to find out the pairs which make a perfect square.
For example in:
a = [2, 6, 10, 13, 17, 18]
b = [3, 7, 8, 9, 11, 15]
There are two pairs (2,8) and (8,18).
Is there any method efficient than the brute-force? Here is my code which has a time complexity of O(n*m) (where n is the length of a and m is the length of b).
pl = []
a = [ 2, 6, 10, 13, 17,18]
b = [ 3, 7, 8, 9, 11, 15 ]
i = 0
while(i < len(a)):
j = 0
while(j < len(b)):
p = a[i]*b[j]
n = p**0.5
u = int(n)
if n == u:
pl.append((a[i],b[j]))
j = j+1
i = i+1
print(pl)
This question has been asked before using C# here, but I don't get what they mean by "All we would need to store for each number is which of its prime factors have an odd count", so I can't implement this in my Python code.
Can someone explain to me how we might implement an efficient solution in Python?
The logic described in the linked question is as follows. A perfect square's prime factors will always be in pairs. For example,
36 = 2*2*3*3. We have two3s and two2s. Therefore, if we take any two numbers that multiply to form a perfect square, if we take the combined counts of each of their prime factors, we will also get even counts.For example,
8 = 2*2*2, and18 = 2*3*3. Combined, we get four2s and two3s.Below is some Python code that implements this algorithm, using
collections.Counterand sets to remove duplicates. First, we precompute all prime factorizations for each unique element inaandbto avoid redundancy, and store this in a dictionary. Then, we loop over pairs of elements fromaandb, usingitertools.product, and combine the prime factor counts. If every count is even, we add the sorted pair to a set.Code:
Output: