in reply to Triangle Numbers Revisited
This is blazingly fast with numbers even several orders of magnitude larger than 987654321, and requires almost no memory to run.use strict; use warnings; my ($i, $j, $inum, $jnum, $left); $| = 1; print "Enter the number to check : "; my $inp = <STDIN>; BING: for ($i = tget($inp); $i; $i--) { # BUG ON THIS LINE - SEE BELOW FOR F +IX $inum = tmake($i); $left = tget($inp - $inum - 1) + 1; for ($j = 1; $j < $left; $j++) { $jnum = tmake($j); last BING if (tis($inp - $inum - $jnum)); } } print " Your triangles are : $inum $jnum " . ($inp - $inum - $jnum) . "\n"; sub tget { return int(sqrt(1 + $_[0] * 2) - .5); } sub tmake { return (.5 * $_[0] * ($_[0] + 1)); } sub tis { my $n = shift; return ($n == tmake(tget($n))); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Triangle Numbers Revisited
by Limbic~Region (Chancellor) on Oct 14, 2004 at 11:29 UTC | |
by TedPride (Priest) on Oct 14, 2004 at 11:52 UTC |