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

六月ゝ 毕业季﹏ 提交于 2020-05-23 06:58:31

问题


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)].


回答1:


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]



回答2:


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)



回答3:


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]


来源:https://stackoverflow.com/questions/5504848/what-is-the-easiest-way-to-get-a-list-of-whole-factor-pairs-of-a-given-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!