I have developed a function that finds the factors of any given number and displays them as pairs. I am now wanting to check if there are at least two pairs of factors where the sum of one of the pairs is equal to the difference of another pair. Pairs are the factors of one specific number. For instance, the number 6 would work as 2+3 = 6-1. I’m not sure how to start the code without importing. I’ve included my code for finding the factor pairs.
def Factors(value):
factors = []
for i in range(1, int(value**0.5)+1):
if value % i == 0:
factors.append((i, value // i))
return factors
>Solution :
Try to use itertools.combinations:
from itertools import combinations
x = # your number
for p1, p2 in combinations(Factors(x), 2):
if sum(p1) == abs(p2[0] - p2[1]) or sum(p2) == abs(p1[0] - p1[1]):
print(p1, p2)
This is a solution implementing a great suggestion from @ScottHunter (its complexity is O(n)):
x = # this is your number, 6 for example
f = Factors(x)
dct = {}
for p in f:
s = sum(p)
if s in dct:
dct[s].append(p)
else:
dct[s] = [p]
for p1 in f:
d = abs(p1[0] - p1[1])
if d in dct:
print(*((p1, p2) for p2 in dct[d]))