So I finished problem 12 from Project Euler. I made it via a brute force attack in Perl.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import math
triangle = 0
for x in range ( 1 , 100000 ):
triangle = x * (x + 1 ) / 2
def primefactors(x):
factorlist = []
loop = 2
while loop< = x:
if x % loop = = 0 :
x / = loop
factorlist.append(loop)
else :
loop + = 1
return factorlist
divisor = 1
for z in set (primefactors(triangle)):
divisor = (primefactors(triangle).count(z) + 1 ) * divisor
if (divisor > 500 ):
print "Triangle" , triangle, " has " , divisor, " divisors."
quit()
|
Reference:
1) Integer Factorization
2) Triangular numbers
3) Number of divisors of a number