如何打印数字因子?

时间:2013-09-16 01:33:06

标签: python math

我对python中的倍数有疑问。有谁知道如何让程序打印一定数量的倍数?就像我把它们放在“10”中一样,它应该打印“1,10,2,5”或类似的东西 感谢

2 个答案:

答案 0 :(得分:2)

非常天真,你可以测试每个数字,最多n(10)

n = 10
results = []
for i in range(1,n+1):
    if n % i == 0:
        results.append(i)
print(results)

或者作为列表理解:

n = 10
print([x for x in range(1,n+1) if n % x == 0])

但实际上你只需要测试n的sqrt。使用简单的生成器:

def divisor(n):
    a = 1
    l = n ** 0.5
    while a <= l:
        if n % a == 0:
            if a == n//a:
                yield a,
            else:
                yield a, n//a
        a += 1

print([x for a in divisor(10) for x in a])
print(sorted(x for a in divisor(10) for x in a))  # Sorted

答案 1 :(得分:1)

你走了:

from collections import defaultdict
from math import sqrt

def factor(n):
    i = 2
    limit = sqrt(n)    
    while i <= limit:
      if n % i == 0:
        yield i
        n = n / i
        limit = sqrt(n)   
      else:
        i += 1
    if n > 1:
        yield n

def factorGenerator(n):
    d=defaultdict(int)
    for f in factor(n):
        d[f]+=1
    return [(e,d[e]) for e in sorted(d.keys())]

def divisorGen(n):
    factors = factorGenerator(n)
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
                break
            f[i] = 0
            i += 1
            if i >= nfactors:
                return

print list(divisorGen(10)) 

打印:

[1, 2, 5, 10]