#!/usr/bin/perl -w # -*-Perl-*- use strict; sub triangular { use integer; my \$n=shift; \$n*(\$n+1)/2; } my @threedigit = map triangular(\$_), (int(sqrt(2*100))..int(sqrt(2*1000))); my @fivedigit = map triangular(\$_), (int(sqrt(2*10000))..int(sqrt(2*100000))); print "There are ".scalar @threedigit." three digit triangular numbers\n"; print "There are ".scalar @fivedigit." five digit triangular numbers\n"; my @threes; for (@threedigit){ \$_ !~ m/(\d)\d*\1/g and push @threes,\$_; } @threedigit = @threes; @threes = (); print "There are ".scalar @threedigit." three digit ones which lack matching digits.\n"; my @fives; for (@fivedigit){ \$_ =~ m/^\d*(\d)\1\$/ and \$_ !~ m/^\d*(\d)\d*\1\d+\$/g and push @fives,\$_;} @fivedigit = @fives; @fives = (); print "There are ".scalar @fivedigit." five digit ones matching the pattern 'THREE'.\n"; my @THREE; my @TEN; # eliminate fives which dont give a TEN for (@fivedigit) { my \$t5 = \$_; my (\$T,\$H,\$R,\$E) = split //,\$t5; my \$N = "[^\$T\$H\$R\$E]"; for (@threedigit) { my \$t3 = \$_; my @t3 = split //, \$t3; if (\$t3 =~ m/\$T\$E\$N/){ \$N=\$t3[2]; push @threes, \$t3; push @fives, \$t5; } } } # Now Brute Force my \$size = \$#fives; my %solution = ('THREE'=>[],'TEN'=>[],'ONE'=>[],'SIX'=>[]); my \$idx; for \$idx (0..\$size) { my (\$T,\$H,\$R,\$E) = split //, \$fives[\$idx]; my (\$XT,\$XE,\$N) = split //, \$threes[\$idx]; my \$cc = "[^\$T\$H\$R\$E\$N]"; for (@threedigit){ my \$num = \$_; if (\$num =~ m/\$cc\$N\$E/){ my \$O = (split //, \$num)[0]; my \$cc="[^\$T\$H\$R\$E\$N\$O]"; for (@threedigit){ if (\$_ =~ /\$cc{3}/){ my (\$S,\$I,\$X) = split //, \$_; push @{\$solution{'THREE'}}, \$fives[\$idx]; push @{\$solution{'TEN'}}, \$threes[\$idx]; push @{\$solution{'ONE'}}, \$num; push @{\$solution{'SIX'}}, \$_; } } } } } # write out solution and timings for (keys %solution) { print "\$_:\t",join("\t",@{\$solution{\$_}}),"\n"; } my @tim = times(); print "Elapsed time:\t",join "\t", @tim,"\n";