Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a sum of one pair of a factor is equal to the difference of another pair?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading