So I finished problem 12 from Project Euler. I made it via a brute force attack in Perl.
#!/usr/bin/env perl use warnings; use strict; my $j = 0; for (my $x=1; $x <= 1000000; $x++) { $j = $j + $x; my $dividend = 0; print "j is $j, x is $x and dividend is $dividend.\n"; for (my $z=1; $z <= ($j + 1); $z++) { if ($j%$z == 0) { $dividend = $dividend + 1; print "$z is dividend of $j and $j has dividend $dividend.\n"; if ($dividend > 501) { print "$z is dividend of $j and $j has dividend $dividend.\n"; exit; } } } }
and with some logic in Python. The python script can be divided in three part, first we find the triangle number, then we calculate the numbers that factor the triangle number and place it into an array and the last step would be to calculate how many divisors the triangle number has.
#!/usr/bin/python import math # Start the triangle by one triangle = 0 for x in range(1, 100000): triangle = x*(x+1)/2 #print "triangles is ", triangle # We factor the triangle into prime numbers def primefactors(x): factorlist=[] loop=2 while loop<=x: if x%loop==0: x/=loop factorlist.append(loop) else: loop+=1 return factorlist #print primefactors(triangle) # We calculate the number of divisors of the triangle number divisor = 1 for z in set(primefactors(triangle)): #print "{0}\t{1}".format(z,primefactors(triangle).count(z)) divisor = (primefactors(triangle).count(z) + 1) * divisor #print "Triangle", triangle," has ", divisor," divisors." if (divisor > 500): print "Triangle", triangle," has ", divisor," divisors." quit()
Reference:
1) Integer Factorization
2) Triangular numbers
3) Number of divisors of a number