找到具有n个因子的第一个三角形数

时间:2013-12-27 18:36:32

标签: python

我正在尝试打印具有n个因子的第一个三角形数字,但是当我运行以下代码时

def mostFactors(limit):
    triangulars = []
    factors = []
    most_factors = []

    for i in range(2, 1000):
        sum = 0
        for j in range(1, i):
            sum += j
        triangulars.append(sum)    

    for i in triangulars:
        if len(most_factors) == limit:
            return most_factors
            break        
        for j in range(1, i+1):
            if i % j == 0:
                factors.append(j)
                print (i,factors)
            if len(factors) > len(most_factors):
                most_factors = factors
                factors = []

mostFactors(30)

这是我运行程序时的前几行输出,显然并非列表中的所有元素都是因子,并且并未列出所有实际因素

Triangular number [factors]
1 [1]
3 [1]
3 [1, 3]
6 [1]
6 [1, 2]
6 [1, 2, 3]
6 [6]
10 [6, 1]
10 [6, 1, 2]
10 [6, 1, 2, 5]
10 [10]
15 [10, 1]
15 [10, 1, 3]
15 [10, 1, 3, 5]

2 个答案:

答案 0 :(得分:1)

这样做你想要的吗?如果您正在使用

,请将print语句更改为python3格式
def mostFactors(limit):
    triangulars = []
    factors = []
    most_factors = []

    for i in range(2, 10):
        sum = 0
        for j in range(1, i):
            sum += j
        triangulars.append(sum)    

    for i in triangulars:
        if len(most_factors) == limit:
            return most_factors
            break        
        for j in range(1, i+1):
            if i % j == 0:
                factors.append(j)
            if len(factors) > len(most_factors):
                most_factors = factors
        print i,factors
        factors = []

答案 1 :(得分:0)

您的部分问题是,您要检查ji的因素是否错误。您想要i % j