There's more than one way to do things PerlMonks

### Re: Triangle Numbers Revisited

by TedPride (Priest)
 on Oct 14, 2004 at 10:25 UTC ( #399153=note: print w/replies, xml ) Need Help??

in reply to Triangle Numbers Revisited

```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))); }
This is blazingly fast with numbers even several orders of magnitude larger than 987654321, and requires almost no memory to run.

Replies are listed 'Best First'.
Re^2: Triangle Numbers Revisited
by Limbic~Region (Chancellor) on Oct 14, 2004 at 11:29 UTC
TedPride,
This is blazingly fast...

I wanted to see just how fast, so I modified your code to fit into the benchmark FoxtrotUniform and I were playing with. It turns out your code is only about half as fast as my second version and it has a bug I didn't bother to track down. To see the bug, try entering 3133756 with your code.

I say your code is only about half as fast because it got less than halfway through (line 2235 of 5000) when it blew up and it took approximately the same amount of time (3.619 seconds) to get there.

In case you want to run some more tests yourself, take a look at gen_targets.pl and then use this modified code:

Cheers - L~R

I found and fixed the bug. See my second version. As to it being blazingly fast, it is blazingly fast - just not as blazingly fast as it could be if I took the time to optimize the algorithm. Congrats if yours is faster.

Create A New User
Node Status?
node history
Node Type: note [id://399153]
help
Chatterbox?
and the rats come out to play...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2017-08-22 23:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (344 votes). Check out past polls.

Notices?