开发者

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

开发者 https://www.devze.com 2023-02-20 22:24 出处:网络
What is the easiest way to get a list of whole factor p开发者_JAVA技巧airs of a given integer? For example: f(20) would return [(1,20), (2,10), (4,5)].def f(value):

What is the easiest way to get a list of whole factor p开发者_JAVA技巧airs of a given integer?

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


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]


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)


How about this:

def f(n):
    from itertools import takewhile
    if not isinstance(n,int):
          raise ValueError("supplied %s type, requires integer input" %(type(n).__name__))
    return [(i,n/i) for i in takewhile(lambda x:x*x<n,xrange(1,n)) if (n%i)==0]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号