I’m just not getting into large enough numbers. It’s also taking a really long time to crunch through all this data. I’m thinking I need a new approach. I’m considering two different options. First, cut down on the number crunching. I’ve already added a shortcut to count the number of factors (only need to test up through the sqrt of the number, then mult by 2). Second, consider going the opposite direction. Instead of finding all the triangular numbers and testing if they have over 500 divisors, find all numbers that have over 500 divisors and see if they are triangular.
from time import time
start_time= time()
tri_num = 0
tri_fact= 0
for i in range(10000):
print i
tri_num= tri_num+i
for j in range(1, (tri_num+1)):
if tri_num%j==0:
tri_fact= tri_fact+1
if tri_fact>500:
print tri_num, 'Here is the answer!'
break; break; break
else:
tri_fact= 0
if tri_fact==0:
print 'Sorry, try next time!'
end_time= time()
elapse_time= end_time - start_time
print elapse_time
Wikipedia reminded me of the formula for finding the nth triangular number.
After fixing a stupid mistake in the code, this worked like a charm. I realize that it is the “brute force” method, but I’m happy that I at least gathered the simplest way to count the number of factors of any given number. I’m also getting much better with Python. Glad to be done with this one though, it was plaguing me all day!
from time import time
start_time= time()
print 'Process started'
for i in range(10000, 100000):
tri_num= (i*(i+1))/2
tri_fact= 0
for j in range(1, int((tri_num**0.5)+1)):
if tri_num%j==0:
tri_fact= tri_fact+2
if j*j==tri_num:
tri_fact= tri_fact-1
print i, tri_num, tri_fact
if tri_fact>500:
print tri_num, 'Here is the answer!'
break; break; break
end_time= time()
elapse_time= end_time - start_time
print elapse_time, 'seconds have passed'