I'm a beginner to programming and just started python, I've been trying to work through Project Euler challenges.
I wrote a program to solve Project Euler #12, which asks for the smallest number of the form 1+ 2 + 3 + … + n which has over 500 divisors. It works perfectly with smaller numbers like 100, but takes too long trying to find up to 500 factors. I gave up waiting after about 20 minutes. I'd like some help with optimizing my code to make it faster.
I basically made a function that finds the triangular number of a given number and another function that counts the number of factors/divisors of a number. I made a while loop where a number keeps increasing till the triangular number of itself has more than 500 factors.
And here is my code:
#Starts the timer to measure time taken for code to run:
import time
start_time = time.time()
#Returns the triangular number of 'num':
def triangular(num):
return int((num*(num+1))/2)
#Returns the number of factors(divisors) of 'num':
def facCount(num):
summ = 0
for i in range(1, num+1):
if num % i == 0:
summ += 1
return summ
#Declares x (starting value):
x = 0
#main:
while True:
#Checks if number of factors for the triangular of x is above 500
if facCount(triangular(x)) > 500:
#Sets the value of 'ans' to the triangular of 'x':
ans = triangular(x)
#Exits the loop since answer is found
break
x += 1
#Prints answer (the first triangular number that has more than 500 factors):
print(ans)
#Prints the time taken for code to execute:
print("--- %s seconds ---" % (time.time() - start_time))