Possible Spoiler Warning
I’ve spent ages trying to improve this algorithm and work out what’s going wrong, but I can’t seem to work out why the outputted answer is incorrect.
I’m trying to solve Project Euler #12, to get the lowest triangular number to have over 500 divisors, but it says my answer is incorrect.
Here is my Python code:
import time
# function to get the number of divisors
def div(n):
d=2
for i in range(2,int(n**.5)+2):
if (n % i) == 0:
d += 1
return d
start = time.time()
w = True
n=m=1
while w:
n += 1
s = (n*(n+1))/2 # nth triangle number
r = div(s)
if r > m:
m = r
print s,"has",r,"divisors"
if r > 500:
w = False
print "Solved in",((time.time()-start)*1000),"milliseconds"
And the output for that code is this (in 66 seconds):
3 has 2 divisors
6 has 4 divisors
36 has 6 divisors
120 has 9 divisors
…
76576500 has 289 divisors
103672800 has 325 divisors
236215980 has 385 divisors
842161320 has 513 divisors
Solved in 65505.5799484 milliseconds
However, if I input 842161320 into the Project Euler problem, it says it’s incorrect.
What am I doing wrong?
I see two bugs:
divfunction is broken:div(24) == 5, while it should be 83, although it should be1You could implement a working
divlike this:Also, that code is inefficient as hell, some suggestions to improve it are:
Instead of calculating the
nth triangular number using your formula, use a rolling sum:Also, Use prime factors to calculate the number of divisors. You can create a prime factor cache for maximum performance.