Note that there are some explanatory texts on larger screens.

plurals
  1. POImproving my code for project euler p12. in Python
    text
    copied!<p>I am doing project Euler.problem twelve and have come up with the following code, which works fine when tested against low numbers: </p> <pre><code>def highlyDivisibleTriangularNumber(n): """ triangular num formula: x(x-1)/2 e.g 5th triang num: x5 = 5(5+1)/2 = 15 :param n: """ divisors = [x for x in xrange(1, 31)] count = 0 for i in xrange(1, n): triangNum = (i* (i+1)/2) # create triangular number based on formula: x(x-1)/2 for div in divisors: if triangNum % div == 0: # if triangular number modulo div equals 0 the add it to highestDivisors count +=1 if count == 6: # if count is equal to 6 then we have found the required number so return it. return triangNum else: if div == 30: # else if we have have reached the last divisor, reset count to zero count = 0 print(highlyDivisibleTriangularNumber(100)) </code></pre> <p>I would appreciate some pointers on how to improve efficiency, where I am going wrong and also in regard to setting the divisor upper limit. I am sure from a maths perspective, there are no doubt many ways to improve the code. Thanks.</p> <p>The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:</p> <p>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...</p> <p>Let us list the factors of the first seven triangle numbers:</p> <p>1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors.</p> <p>What is the value of the first triangle number to have over five hundred divisors?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload