简体   繁体   中英

Finding the first triangular number with n factors

I am trying to print the first triangular number that has n factors, but when I run the following piece of code

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)

This is the first few lines of output when I run the program and it's obvious that not all the elements in the lists are factors, and that not all of the actual factors are listed

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]

Does this do what you want? Change print statement to python3 format if that is what you're using

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 = []

Part of your problem is that you're checking to see if j is a factor of i incorrectly. You want i % j instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM