Kaprekar numbers: Difference between revisions

Content added Content deleted
No edit summary
m (→‎Numeric version (medium): added '.race' for concurrency)
Line 3,292: Line 3,292:
<pre>1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999</pre>
<pre>1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999</pre>
===Numeric version (medium)===
===Numeric version (medium)===
<lang perl6>sub kaprekar( Int $n, Int :$base = 10 ) {
The addition of <tt>'''race'''</tt>, in two places, allows for concurrent computation, and brings a significant speed-up in running time. <lang perl6>sub kaprekar( Int $n, Int :$base = 10 ) {
my $hi = $n ** 2;
my $hi = $n ** 2;
my $lo = 0;
my $lo = 0;
Line 3,305: Line 3,305:
print " $_" if .&kaprekar for ^10_000;
print " $_" if .&kaprekar for ^10_000;


my $n;
say "\n\nBase 10 Kaprekar numbers < :10<1_000_000> = ", [+] (1 if kaprekar $_ for ^1000000);
(^1_000_000).race.map: { $n++ if kaprekar $_ }
say "\n\nBase 10 Kaprekar numbers < :10<1_000_000> = $n";


say "\nBase 17 Kaprekar numbers < :17<1_000_000>";
say "\nBase 17 Kaprekar numbers < :17<1_000_000>";
Line 3,311: Line 3,313:
my &k17 = &kaprekar.assuming(:base(17));
my &k17 = &kaprekar.assuming(:base(17));


my @results;
for ^:17<1000000> -> $n {
(^:17<1_000_000>).race.map: -> $n {
my ($h,$l) = k17 $n;
my ($h,$l) = k17 $n;
next unless $l;
next unless $l;
Line 3,317: Line 3,320:
my $s17 = ($n * $n).base(17);
my $s17 = ($n * $n).base(17);
my $h17 = $h.base(17);
my $h17 = $h.base(17);
say "$n $n17 $s17 ($h17 + $s17.substr(* - $h17.chars))";
@results.push: "$n $n17 $s17 ($h17 + $s17.substr(* - max(1,($s17.chars - $h17.chars))))";
}
}</lang>

.say for @results.sort({$^a.chars <=> $^b.chars});</lang>
{{out}}
{{out}}
<pre> 1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
<pre style="height:35ex">1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999


Base 10 Kaprekar numbers < :10<1_000_000> = 54
Base 10 Kaprekar numbers < :10<1_000_000> = 54
Line 3,383: Line 3,388:
24137568 GGGGGG GGGGGF000001 (GGGGGF + 000001)</pre>
24137568 GGGGGG GGGGGF000001 (GGGGGF + 000001)</pre>
Note that this algorithm allows the null string on the left, taken as zero, which automatically includes 1 as the first element of the sequence.
Note that this algorithm allows the null string on the left, taken as zero, which automatically includes 1 as the first element of the sequence.

===Casting out nines (fast)===
===Casting out nines (fast)===
<lang perl6>sub kaprekar-generator( :$base = 10 ) {
<lang perl6>sub kaprekar-generator( :$base = 10 ) {