Taxicab numbers: Difference between revisions

m
→‎{{header|Perl 6}}: Move some calculations out of hot loop, general speedup tweaks
m (re-instated an image denoting the first taxi-cab number that was elided.)
m (→‎{{header|Perl 6}}: Move some calculations out of hot loop, general speedup tweaks)
Line 2,195:
=={{header|Perl 6}}==
This uses a pretty simple search algorithm that doesn't necessarily return the Taxicab numbers in order. Assuming we want all the Taxicab numbers within some range S to N, we'll search until we find N values. When we find the Nth value, we continue to search up to the cube root of the largest Taxicab number found up to that point. That ensures we will find all of them inside the desired range without needing to search arbitrarily or use magic numbers. Defaults to returning the Taxicab numbers from 1 to 25. Pass in a different start and end value if you want some other range.
<lang perl6>subconstant MAIN ($start@cu = 1,(^Inf).map: $end{ = 25) {}
 
sub MAIN ($start = 1, $end = 25) {
my %taxi;
my int $taxis = 0;
my $terminate = 0;
my int $max = 0;
 
for 1 .. * -> $c1 {
display(last %taxi,if ?$start,terminate $end ) and exit if 0 <&& ($terminate < $c1);
my $c = $c1 ** 3;
for 1 .. $c1 -> $c2 {
my $this = @cu[$c2 ** 3c1] + @cu[$cc2];
%taxi{$this}.push: [$c2, $c1];
$taxis++ if %taxi{$this}.elems == 2; {
++$taxis;
$terminate = %taxi.grep( { $_.value.elems > 1 } ).sort( +*.key )[*-1].key**(1/3)
if $taxismax max== $end and !$terminatethis;
}
$terminate = ceiling $max ** (1/3) if $taxis == $end and !$terminate;
my} $c = $c1 ** 3;
}
 
display( %taxi, $start, $end );
 
}
 
sub display (%this_stuff, $start, $end) {
my $i = $start;
printf "%4d %10d =>\t%s\n", $i++, $_.key,
($_.value.map({ sprintf "%4d³ + %-s", |$_[0], "$_[1]\³" })).join: ",\t"
for %this_stuff.grep( { $_.value.elems > 1 } ).sort( +*.key )[$start-1..$end-1];
1;
}</lang>
{{out}}With no passed parameters (default):
10,333

edits