-5

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

4

2 回答 2

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
于 2013-09-16T01:40:38.800 回答
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]   
于 2013-09-16T01:41:40.760 回答