perlquestion
Limbic~Region
All,
<br />
[YuckFoo] once [161681|asked] if there was a more efficient way to verify that any non-negative whole integer could be represented as the sum of 3 triangular numbers. [particle] came up with a pretty cool [161737|solution] using bit strings. While fast, it blew up when I asked it for 987654321.
<p>
My usual approach to these kind of problems is to translate how I would solve the problem with a pencil and paper in code, make any obvious performance changes, and see if it is fast enough. I usually don't start thinking about more efficient algorithms unless it is a "challenge" or my initial approach was just plain abysmal. Here was my go at it:
</p>
<readmore>
<CODE>
#!/usr/bin/perl
use strict;
use warnings;
my $target = defined $ARGV[0] ? $ARGV[0] : 987654321;
print join ', ' , get_three( $target );
sub get_three {
my $num = shift;
my $prev = p_tri( $num );
return ($num, 0, 0) if ! $prev;
while ( $prev ) {
my $p_tri = ($prev * $prev + $prev) / 2;
my $i = 0;
my $j = $num - $p_tri;
while ( $j >= $i ) {
return $p_tri, $i, $j if ! p_tri( $i ) && ! p_tri( $j );
++$i;
--$j;
}
--$prev;
}
die "Something went horribly wrong : $num\n";
}
sub p_tri {
my $num = shift;
my $x = ( sqrt( 8 * $num + 1 ) + 1 )/ 2;
my $t = int $x;
return $t == $x ? 0 : --$t;
}
</CODE>
</readmore>
<p>
Now without explaining how this works<sup>*</sup>, I will ask the same question as [YuckFoo] - <i>Any suggestions to optimize the search method?</i>
</p>
<div class="pmsig"><div class="pmsig-180961">
<p>
Cheers - [Limbic~Region|L~R]
</p>
</div></div>
<small>* If anyone wants to know, feel free to ask. If anyone wants to offer their own explanation, feel free to post.
</small>