Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to get a list of whole factor pairs of a given integer?

Tags:

python

math

What is the easiest way to get a list of whole factor pairs of a given integer?

For example: f(20) would return [(1,20), (2,10), (4,5)].

like image 358
Christopher O'Donnell Avatar asked Dec 09 '22 09:12

Christopher O'Donnell


2 Answers

def f(value):
    factors = []
    for i in range(1, int(value**0.5)+1):
        if value % i == 0:
            factors.append((i, value / i))
    return factors

Or the same thing using a list comprehension:

def f(val):
    return [(i, val / i) for i in range(1, int(val**0.5)+1) if val % i == 0]
like image 135
Steve Mayne Avatar answered May 12 '23 17:05

Steve Mayne


Or this:

def f(n):
        factors_list = []
        for i in xrange(1, int(n**0.5) + 1):
            if n % i == 0:
                factors_list.append((i, n/i))
        return factors_list

print f(20)

EDIT: Or in a one-liner using list comprehension:

def f(n):
    return [(i, n / i) for i in xrange(1, int(n**0.5) + 1) if n % i == 0]

print f(36)

EDIT2: If you want the function to work for negative integers (as well as 0 and positive integers) use:

def f(n):
    return [(i, n / i) for i in xrange(1, int(math.sqrt(math.fabs(n))) + 1) if n % i == 0]

print f(-36)
like image 24
Benjamin Avatar answered May 12 '23 19:05

Benjamin