Reputation: 729
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]
Upvotes: 0
Views: 115
Reputation: 6365
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 = []
Upvotes: 1
Reputation: 37344
Part of your problem is that you're checking to see if j
is a factor of i
incorrectly. You want i % j
instead.
Upvotes: 0