Hi, I'm trying to solve Euler problem #12 which is 'What is the value of the first triangle number to have over five hundred divisors?' (A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...)I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster. Thanks.
import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
-
You're not updating the value of
one, so your program will never end.J.F. Sebastian : I think it is @mark lincoln's idiom for `while True`. And considering the problem `while True` is appropriate here. He needs just to add a `break` after `print`, fix couple of bugs and the solution will work (although too slow).Andy Mikula : I agree - returning after the print would do the trick, at least as far as that part goes. I personally try to stay away from while true because I have a nasty habit of forgetting to return things :P -
Hints:
- what is the formula for
n-th triangular number? nandn+1have no common factors (except1). Question: given number of factors innandn+1how to calculate number of factors inn*(n+1)? What aboutn/2and(n+1)(ornand(n+1)/2)?- if you know all prime factors of
nhow to calculate number of divisors ofn?
If you don't want to change your algorithm then you can make it faster by:
- replace
l.appendbyfactor_count += 1 - enumerate to
int(a**.5)instead ofa/2(usefactor_count += 2in this case).
starblue : You are giving away too much of the solution.nimrodm : But he is giving good directions! (unlike the above almost brute force solution of Ghose).S.Lott : +1: Very, very helpful hints. Especially the prime factors to number of divisors -- genius.J.F. Sebastian : I've posted solution based on the above hints http://gist.github.com/68515 - what is the formula for
-
You'll have to think more and use less brute force to solve Project Euler questions.
In this case you should investigate which and how many divisors triangle numbers have. Start at the beginning, look for patterns, try to understand the problem.
-
Just for sanity's sake, you should use
while True:and get rid of
one.marc lincoln : yeah thanks ill make sure not to use that again. -
Your current brute force algorithm is too inefficient to solve this problem in the Project Euler time limit of 1 minute. Instead, I suggest looking at the Divisor Function:
http://www.artofproblemsolving.com/Wiki/index.php/Divisor_function
0 comments:
Post a Comment