Jump to content

Kaprekar numbers: Difference between revisions

m
→‎Numeric version (medium): added '.race' for concurrency
No edit summary
m (→‎Numeric version (medium): added '.race' for concurrency)
Line 3,292:
<pre>1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999</pre>
===Numeric version (medium)===
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 $lo = 0;
Line 3,305:
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> = ", [+] (1 if kaprekar $_ for ^1000000)n";
 
say "\nBase 17 Kaprekar numbers < :17<1_000_000>";
Line 3,311 ⟶ 3,313:
my &k17 = &kaprekar.assuming(:base(17));
 
my @results;
for ^:17<1000000> -> $n {
(^:17<1_000_000>).race.map: -> $n {
my ($h,$l) = k17 $n;
next unless $l;
Line 3,317 ⟶ 3,320:
my $s17 = ($n * $n).base(17);
my $h17 = $h.base(17);
say@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}}
<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
Line 3,383 ⟶ 3,388:
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.
 
===Casting out nines (fast)===
<lang perl6>sub kaprekar-generator( :$base = 10 ) {
2,392

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.