Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

triangle numbers in python

Tags:

python

I'm trying to solve the problem:

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()
like image 526
marc lincoln Avatar asked Feb 20 '09 22:02

marc lincoln


3 Answers

Hints:

  • what is the formula for n-th triangular number?
  • n and n+1 have no common factors (except 1). Question: given number of factors in n and n+1 how to calculate number of factors in n*(n+1)? What about n/2 and (n+1) (or n and (n+1)/2)?
  • if you know all prime factors of n how to calculate number of divisors of n?

If you don't want to change your algorithm then you can make it faster by:

  • replace l.append by factor_count += 1
  • enumerate to int(a**.5) instead of a/2 (use factor_count += 2 in this case).
like image 121
jfs Avatar answered Oct 28 '22 23:10

jfs


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.

like image 39
starblue Avatar answered Oct 28 '22 22:10

starblue


You're not updating the value of one, so your program will never end.

like image 5
Andy Mikula Avatar answered Oct 28 '22 21:10

Andy Mikula