Casting out nines: Difference between revisions

no edit summary
No edit summary
 
(35 intermediate revisions by 16 users not shown)
Line 1:
{{task}}
[[Category:Checksums]]
{{task}}
 
;Task   (in three parts):
Line 6:
 
;Part 1
Write a procedure (say <math>\mathit{co9}(x)</math>) which implements [https://web.archive.org/web/20120619091249/http://mathforum.org/library/drmath/view/55926.html Casting Out Nines] as described by returning the checksum for <math>x</math>. Demonstrate the procedure using the examples given there, or others you may consider lucky.
 
Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.
 
With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.
 
;Part 2
Line 28 ⟶ 32:
* [[Kaprekar numbers]]
<br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F CastOut(Base, Start, End)
V ran = (0 .< Base - 1).filter(y -> y % (@Base - 1) == (y * y) % (@Base - 1))
V (x, y) = divmod(Start, Base - 1)
[Int] r
L
L(n) ran
V k = (Base - 1) * x + n
I k < Start
L.continue
I k > End
R r
r.append(k)
x++
 
L(v) CastOut(Base' 16, Start' 1, End' 255)
print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 10, Start' 1, End' 99)
print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 17, Start' 1, End' 288)
print(v, end' ‘ ’)
print()</syntaxhighlight>
 
{{out}}
<pre>
1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288
</pre>
=={{header|360 Assembly}}==
{{trans|REXX}}
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Casting out nines 08/02/2017
CASTOUT CSECT
USING CASTOUT,R13 base register
Line 95 ⟶ 131:
XDEC DS CL12 temp for xdeco
YREGS
END CASTOUT</langsyntaxhighlight>
{{out}}
<pre>
Line 106 ⟶ 142:
451 459 460 468 469 477 478 486 487 495 496
</pre>
=={{header|ABC}}==
<syntaxhighlight lang="abc">
\ casting out nines - based on the Action! sample
 
HOW TO ADD v TO n: PUT n + v IN n
 
PUT 10, 2, 0, 0 IN base, n, count, total
FOR i IN { 1 .. base ** n }:
ADD 1 TO total
IF i mod ( base - 1 ) = ( i * i ) mod ( base - 1 ):
ADD 1 TO count
WRITE i
WRITE // "Trying", count, "numbers instead of", total, "numbers saves"
WRITE 100 - ( ( 100 * count ) / total ), "%" /
</syntaxhighlight>
{{out}}
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
 
Trying 23 numbers instead of 100 numbers saves 77 %
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">INT FUNC Power(INT a,b)
INT i,res
 
res=1
FOR i=1 TO b
DO
res==*a
OD
RETURN (res)
 
PROC Main()
DEFINE BASE="10"
DEFINE N="2"
INT i,max,count,total,perc
 
max=Power(BASE,N)
count=0 total=0
FOR i=1 TO max
DO
total==+1
IF i MOD (BASE-1)=(i*i) MOD (BASE-1) THEN
count==+1
PrintI(i) Put(32)
FI
OD
perc=100-100*count/total
PrintF("%E%ETrying %I numbers instead of %I numbers saves %I%%",count,total,perc)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Casting_out_nines.png Screenshot from Atari 8-bit computer]
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
 
Trying 23 numbers instead of 100 numbers saves 77%
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Action!}}
<syntaxhighlight lang="algol68">BEGIN # casting out nines - translated from the Action! sample #
INT base = 10;
INT n = 2;
INT count := 0;
INT total := 0;
FOR i TO base ^ n DO
total +:= 1;
IF i MOD ( base - 1 ) = ( i * i ) MOD ( base - 1 ) THEN
count +:= 1;
print( ( whole( i, 0 ), " " ) )
FI
OD;
print( ( newline, newline, "Trying ", whole( count, 0 )
, " numbers instead of ", whole( total, 0 )
, " numbers saves ", fixed( 100 - ( ( 100 * count ) / total ), -6, 2 )
, "%", newline
)
)
END</syntaxhighlight>
{{out}}
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
 
Trying 23 numbers instead of 100 numbers saves 77.00%
</pre>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">N: 2
base: 10
c1: 0
Line 124 ⟶ 245:
 
print ""
print ["Trying" c2 "numbers instead of" c1 "numbers saves" 100.0 - 100.0*c2//c1 "%"]</langsyntaxhighlight>
 
{{out}}
Line 130 ⟶ 251:
<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Trying 22 numbers instead of 99 numbers saves 77.77777777777777 %</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CASTING_OUT_NINES.AWK
# converted from C
Line 147 ⟶ 267:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 153 ⟶ 273:
Trying 23 numbers instead of 100 numbers saves 77.00%
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="qbasic">base = 10
c1 = 0
c2 = 0
for k = 1 to (base ^ 2) - 1
c1 += 1
if k % (base - 1) = (k * k) % (base - 1) then c2 += 1: print k; " ";
next k
print
print "Trying "; c2; " numbers instead of "; c1; " numbers saves "; 100 - (100 * c2 / c1); "%"
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|GW-BASIC}}
{{works with|QBasic}}
{{works with|Run BASIC}}
{{works with|Just Basic}}
<syntaxhighlight lang="qbasic">100 cls
110 bs = 10 : c1 = 0 : c2 = 0
120 for k = 1 to (bs^2)-1
130 c1 = c1+1
140 if k mod (bs-1) = (k*k) mod (bs-1) then c2 = c2+1 : print k;
150 next k
160 print
170 print "Trying ";c2;"numbers instead of ";c1;"numbers saves ";100-(100*c2/c1);"%"
180 end</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Dim base10 As Integer = 10
Dim c1 As Integer = 0, c2 As Integer = 0, k As Integer
For k = 1 To base10 ^ 2
c1 += 1
If (k Mod (base10 - 1) = (k * k) Mod (base10 - 1)) Then
c2 += 1
Print k; " ";
End If
Next
Print "\nTrying "; c2; " numbers instead of "; c1; " numbers saves "; 100 - (100 * c2 / c1); "%"
End</syntaxhighlight>
 
==={{header|GW-BASIC}}===
The [[#MSX-BASIC|MSX-BASIC]] solution works without any changes.
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS
110 BS = 10 : C1 = 0 : C2 = 0
120 FOR K = 1 TO (BS^2)-1
130 C1 = C1+1
140 IF K MOD (BS-1) = (K*K) MOD (BS-1) THEN C2 = C2+1 : PRINT K;
150 NEXT K
160 PRINT
170 PRINT USING "Trying ## numbers instead of ### numbers saves ##.##%";C2;C1;100-(100*C2/C1)
180 END</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">OpenConsole()
Define.i base, c1, c2, k
 
base = 10
c1 = 0
c2 = 0
For k = 1 To Pow(base, 2) - 1
c1 + 1
If k % (base - 1) = (k * k) % (base - 1)
c2 + 1
Print(Str(k) + " ")
EndIf
Next k
 
PrintN(#CRLF$ + "Trying " + Str(c2) + " numbers instead of " + Str(c1) + " numbers saves " + Str(100 - (100 * c2 / c1)) + "%")
 
PrintN(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">CLS
bs = 10: c1 = 0: c2 = 0
FOR k = 1 TO (bs ^ 2) - 1
c1 = c1 + 1
IF k MOD (bs - 1) = (k * k) MOD (bs - 1) THEN c2 = c2 + 1: PRINT k;
NEXT k
PRINT
PRINT USING "Trying ## numbers instead of ### numbers saves ##.##%"; c2; c1; 100 - (100 * c2 / c1)</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="vb">base = 10
c1 = 0
c2 = 0
for k = 1 to (base ^ 2) - 1
c1 = c1 + 1
if k mod (base - 1) = (k * k) mod (base - 1) then c2 = c2 + 1: print k; " ";
next k
print
print "Trying "; using("##", c2); " numbers instead of "; using("###", c1); " numbers saves "; using("##.##", (100 - (100 * c2 / c1))); "%"
end</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET bs = 10
LET c1 = 0
LET c2 = 0
FOR k = 1 TO (bs^2)-1
LET c1 = c1 + 1
IF REMAINDER(k,(bs-1)) = REMAINDER((k*k),(bs-1)) THEN
LET c2 = c2 + 1
PRINT k;
END IF
NEXT k
PRINT
PRINT USING "Trying ## numbers instead of ### numbers saves ##.##%": c2, c1, 100-(100*c2/c1)
END</syntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Casting out nines"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
bs = 10
c1 = 0
c2 = 0
FOR k = 1 TO (bs ** 2) - 1
INC c1
IF k MOD (bs - 1) = (k * k) MOD (bs - 1) THEN INC c2: PRINT k;
NEXT k
PRINT
PRINT "Trying "; c2; " numbers instead of "; c1; " numbers saves "; 100 - (100 * c2 / c1); "%"
END FUNCTION
END PROGRAM</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">base = 10
c1 = 0
c2 = 0
for k = 1 to (base ^ 2) - 1
c1 = c1 + 1
if mod(k, (base - 1)) = mod((k * k), (base - 1)) then c2 = c2 + 1: print k, " "; : fi
next k
print "\nTrying ", c2 using("##"), " numbers instead of ", c1 using("###"), " numbers saves ", (100 - (100 * c2 / c1)) using("##.##"), "%"
end</syntaxhighlight>
 
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
 
Line 176 ⟶ 455:
printf("\nTring %d numbers instead of %d numbers saves %f%%\n", c2, c1, 100.0 - 100.0 * c2 / c1);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Tring 22 numbers instead of 99 numbers saves 77.777778%</pre>
=={{header|C sharp|C#}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CastingOutNines {
public static class Helper {
public static string AsString<T>(this IEnumerable<T> e) {
var it = e.GetEnumerator();
 
StringBuilder builder = new StringBuilder();
builder.Append("[");
 
if (it.MoveNext()) {
builder.Append(it.Current);
}
while (it.MoveNext()) {
builder.Append(", ");
builder.Append(it.Current);
}
 
builder.Append("]");
return builder.ToString();
}
}
 
class Program {
static List<int> CastOut(int @base, int start, int end) {
int[] ran = Enumerable
.Range(0, @base - 1)
.Where(a => a % (@base - 1) == (a * a) % (@base - 1))
.ToArray();
int x = start / (@base - 1);
 
List<int> result = new List<int>();
while (true) {
foreach (int n in ran) {
int k = (@base - 1) * x + n;
if (k < start) {
continue;
}
if (k > end) {
return result;
}
result.Add(k);
}
x++;
}
}
 
static void Main() {
Console.WriteLine(CastOut(16, 1, 255).AsString());
Console.WriteLine(CastOut(10, 1, 99).AsString());
Console.WriteLine(CastOut(17, 1, 288).AsString());
}
}
}</syntaxhighlight>
{{out}}
<pre>[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]
[1, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 63, 64, 72, 73, 81, 82, 90, 91, 99]
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]</pre>
=={{header|C++}}==
===Filter===
<langsyntaxhighlight lang="cpp">// Casting Out Nines
//
// Nigel Galloway. June 24th., 2012
Line 202 ⟶ 543:
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl;
return 0;
}</langsyntaxhighlight>
{{out|Produces}}
<pre>
Line 249 ⟶ 590:
in this range are included.
===C++11 For Each Generator===
<langsyntaxhighlight lang="cpp">// Casting Out Nines Generator - Compiles with gcc4.6, MSVC 11, and CLang3
//
// Nigel Galloway. June 24th., 2012
Line 292 ⟶ 633:
for (int i : co9(1,99,&r)) { std::cout << i << ' '; }
return 0;
}</langsyntaxhighlight>
{{out|Produces}}
<pre>
Line 298 ⟶ 639:
</pre>
An alternative implementation for struct ran using http://rosettacode.org/wiki/Sum_digits_of_an_integer#C.2B.2B which produces the same result is:
<langsyntaxhighlight lang="cpp">struct ran {
const int base;
std::vector<int> rs;
ran(const int base) : base(base) { for (int nz=0; nz<base-1; nz++) if(SumDigits(nz) == SumDigits(nz*nz)) rs.push_back(nz); }
};</langsyntaxhighlight>
Changing main:
<langsyntaxhighlight lang="cpp">int main() {
ran r(16);
for (int i : co9(1,255,&r)) { std::cout << i << ' '; }
return 0;
}</langsyntaxhighlight>
{{out|Produces}}
<pre>
Line 314 ⟶ 655:
</pre>
Changing main:
<langsyntaxhighlight lang="cpp">int main() {
ran r(17);
for (int i : co9(1,288,&r)) { std::cout << i << ' '; }
return 0;
}</langsyntaxhighlight>
{{out|Produces}}
<pre>
1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288
</pre>
 
=={{header|C#}}==
{{trans|Java}}
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CastingOutNines {
public static class Helper {
public static string AsString<T>(this IEnumerable<T> e) {
var it = e.GetEnumerator();
 
StringBuilder builder = new StringBuilder();
builder.Append("[");
 
if (it.MoveNext()) {
builder.Append(it.Current);
}
while (it.MoveNext()) {
builder.Append(", ");
builder.Append(it.Current);
}
 
builder.Append("]");
return builder.ToString();
}
}
 
class Program {
static List<int> CastOut(int @base, int start, int end) {
int[] ran = Enumerable
.Range(0, @base - 1)
.Where(a => a % (@base - 1) == (a * a) % (@base - 1))
.ToArray();
int x = start / (@base - 1);
 
List<int> result = new List<int>();
while (true) {
foreach (int n in ran) {
int k = (@base - 1) * x + n;
if (k < start) {
continue;
}
if (k > end) {
return result;
}
result.Add(k);
}
x++;
}
}
 
static void Main() {
Console.WriteLine(CastOut(16, 1, 255).AsString());
Console.WriteLine(CastOut(10, 1, 99).AsString());
Console.WriteLine(CastOut(17, 1, 288).AsString());
}
}
}</lang>
{{out}}
<pre>[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]
[1, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 63, 64, 72, 73, 81, 82, 90, 91, 99]
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;;A macro was used to ensure that the filter is inlined.
;;Larry Hignight. Last updated on 7/3/2012.
(defmacro kaprekar-number-filter (n &optional (base 10))
Line 403 ⟶ 679:
(format t "~d potential Kaprekar numbers remain (~~~$% filtered out).~%"
count (* (/ (- stop count) stop) 100))
(if collect (reverse nums))))</langsyntaxhighlight>
{{out}}
<pre>CL-USER> (test :stop 99)
Line 420 ⟶ 696:
36 potential Kaprekar numbers remain (~87.50% filtered out).
(1 16 17 32 33 48 49 64 65 80 ...)</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">precision 4
 
define base = 10, c1 = 0, c2 = 0
 
for k = 1 to (base ^ 2) - 1
 
let c1 = c1 + 1
 
if k % (base - 1) = (k * k) % (base - 1) then
 
let c2 = c2 + 1
print k
 
endif
 
next k
 
print "trying ", c2, " numbers instead of ", c1, " numbers saves ", 100 - (100 * c2 / c1), "%"</syntaxhighlight>
{{out| Output}}<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
trying 22 numbers instead of 99 numbers saves 77.7778%
</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
uint[] castOut(in uint base=10, in uint start=1, in uint end=999999) {
Line 449 ⟶ 748:
castOut(10, 1, 99).writeln;
castOut(17, 1, 288).writeln;
}</langsyntaxhighlight>
{{out|Output (some newlines added)}}
<pre>[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60,
Line 463 ⟶ 762:
 
 
=={{header|FreeBASICEasyLang}}==
{{trans|AWK}}
<lang freebasic>Const base10 = 10
<syntaxhighlight>
Dim As Integer c1 = 0, c2 = 0, k = 1
base = 10
 
Forfor k = 1 Toto base10^2base * base - 1
c1 += 1
if If (k Modmod (base10base - 1) = (k * k) Modmod (base10base - 1)) Then c2 += 1: Print k;" ";
c2 += 1
Next k
write k & " "
 
.
Print
.
Print Using "Intentar ## numeros en lugar de ### numeros ahorra un ##.##%"; c2; c1; 100-(100*c2/c1)
print ""
Sleep</lang>
print "Trying " & c2 & " numbers instead of " & c1 & " numbers saves " & 100 - 100 * c2 / c1
{{out}}
</syntaxhighlight>
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
Intentar 23 numeros en lugar de 100 numeros ahorra un 77.00%
</pre>
 
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">program castout9;
{$ifdef fpc}{$mode delphi}{$endif}
uses generics.collections;
Line 524 ⟶ 819:
co9(1, 10, 99, [1,9,45,55,99]);
co9(1, 10, 1000, [1,9,45,55,99,297,703,999]);
end.</langsyntaxhighlight>
<pre>
Output:
Line 537 ⟶ 832:
Trying 223 numbers instead of 1000 saves 77.70,%.
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Const base10 = 10
Dim As Integer c1 = 0, c2 = 0, k = 1
 
For k = 1 To base10^2
c1 += 1
If (k Mod (base10-1) = (k*k) Mod (base10-1)) Then c2 += 1: Print k;" ";
Next k
 
Print
Print Using "Intentar ## numeros en lugar de ### numeros ahorra un ##.##%"; c2; c1; 100-(100*c2/c1)
Sleep</syntaxhighlight>
{{out}}
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
Intentar 23 numeros en lugar de 100 numeros ahorra un 77.00%
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_base10 = 10
 
void local fn CastingOutNines
NSUInteger i, c1 = 0, c2 = 0
float percent
for i = 1 to _base10^2
c1++
if ( i mod ( _base10 -1 ) == ( i * i ) mod ( _base10 - 1 ) ) then c2++ : printf @"%d \b", i
next
print
percent = 100 -( 100 * c2 / c1 )
printf @"Trying %d numbers instead of %d numbers saves %.2f%%", c2, c1, percent
end fn
 
fn CastingOutNines
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
Trying 23 numbers instead of 100 numbers saves 77.00%
</pre>
 
 
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 706 ⟶ 1,050:
fmt.Println("Valid subset.")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 720 ⟶ 1,064:
Valid subset.
</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">co9 n
| n <= 8 = n
| otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n
Line 728 ⟶ 1,071:
task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100]
 
task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]</langsyntaxhighlight>
 
Auxillary function, returning digits of a number for given base
<langsyntaxhighlight lang="haskell">digits base = map (`mod` base) . takeWhile (> 0) . iterate (`div` base)</langsyntaxhighlight>
 
or using unfolding:
 
<langsyntaxhighlight lang="haskell">digits base = Data.List.unfoldr modDiv
where modDiv 0 = Nothing
modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)</langsyntaxhighlight>
'''Output'''
Line 765 ⟶ 1,108:
λ> quickCheck (\a b -> a > 0 && b > 0 ==> co9 (co9 a * co9 b) == co9 (a*b))
+++ OK, passed 100 tests.</pre>
 
=={{header|J}}==
This is an implementation of: "given two numbers which mark the beginning and end of a range of integers, and another number which denotes an integer base, return numbers from within the range where the number is equal (modulo the base minus 1) to its square". At the time of this writing, this task is a draft task and this description does not precisely match the task description on this page. Eventually, either the task description will change to match this implementation (which means this paragraph should be removed) or the task description will change to conflict with this implementation (so this entire section should be re-written).
<langsyntaxhighlight Jlang="j">castout=: 1 :0
[: (#~ ] =&((m-1)&|) *:) <. + [: i. (+*)@-~
)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight Jlang="j"> 0 (10 castout) 100
0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100</langsyntaxhighlight>
Alternate implementation:
<langsyntaxhighlight Jlang="j">castout=: 1 :0
[: (#~ 0 = (m-1) | 0 _1 1&p.) <. + [: i. (+*)@-~
)</langsyntaxhighlight>
Note that about half of the code here is the code that implements "range of numbers". If we factor that out, and represent the desired values directly the code becomes much simpler:
<langsyntaxhighlight Jlang="j"> (#~ 0=9|0 _1 1&p.) i.101
0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100
(#~ ] =&(9&|) *:) i. 101
0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100</langsyntaxhighlight>
And, of course, we can name parts of these expressions. For example:
<langsyntaxhighlight Jlang="j"> (#~ ] =&(co9=: 9&|) *:) i. 101
0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100</langsyntaxhighlight>
Or, if you prefer:
<langsyntaxhighlight Jlang="j">co9=: 9&|
(#~ ] =&co9 *:) i. 101
0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.*;
import java.util.stream.IntStream;
 
Line 826 ⟶ 1,167:
}
}
}</langsyntaxhighlight>
 
<pre>[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66,
Line 835 ⟶ 1,176:
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160,
161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]</pre>
 
=={{header|JavaScript}}==
===ES5===
Assuming the context of a web page:
<langsyntaxhighlight JavaScriptlang="javascript">function main(s, e, bs, pbs) {
bs = bs || 10;
pbs = pbs || 10
Line 885 ⟶ 1,225:
main(1, 16 * 16 - 1, 16)
main(1, 17 * 17 - 1, 17)
main(parseInt('10', 17), parseInt('gg', 17), 17, 17)</langsyntaxhighlight>
{{Out}}
<pre>start:1 end:99 base:10 printBase:10
Line 910 ⟶ 1,250:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 955 ⟶ 1,295:
.filter(n => (n % k) === (squared(n) % k)))(16)
});
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 1,003 ⟶ 1,343:
]
}</pre>
 
=={{header|jq}}==
{{ works with|jq|1.4}}
Line 1,011 ⟶ 1,350:
 
'''Definition of co9''':
<langsyntaxhighlight lang="jq">def co9:
def digits: tostring | explode | map(. - 48); # "0" is 48
if . == 9 then 0
elif 0 <= . and . <= 8 then .
else digits | add | co9
end;</langsyntaxhighlight>
 
For convenience, we also define a function to check whether co9(i) equals co9(i*i)
for a given integer, i:
<langsyntaxhighlight lang="jq">def co9_equals_co9_squared: co9 == ((.*.)|co9);</langsyntaxhighlight>
 
'''Example''':
Line 1,026 ⟶ 1,365:
Integers in 1 .. 100 satisfying co9(i) == co9(i*i):
 
<langsyntaxhighlight lang="jq">[range (1;101) | select( co9_equals_co9_squared )</langsyntaxhighlight>
produces:
[1,9,10,18,19,27,28,36,37,45,46,54,55,63,64,72,73,81,82,90,91,99,100]
Line 1,035 ⟶ 1,374:
co9_equals_co9_squared condition is by inspection. For the range 1..100 considered above, we have:
 
<langsyntaxhighlight lang="jq">[ range(1;101) | select(is_kaprekar) ]</langsyntaxhighlight>
 
[1,9,45,55,99]
Line 1,041 ⟶ 1,380:
To check the condition programmatically for a given range of integers, we can
define a function which will emit any exceptions, e.g.
<langsyntaxhighlight lang="jq">def verify:
range(1; .)
| select(is_kaprekar and (co9_equals_co9_squared | not));</langsyntaxhighlight>
 
For example, running (1000 | verify) produces an empty stream.
Line 1,052 ⟶ 1,391:
proportion of integers, i, in 1 .. n such that i % (b-1) == (i*i) % (b-1):
 
<langsyntaxhighlight lang="jq">def proportion(base):
def count(stream): reduce stream as $i (0; . + 1);
. as $n
| (base - 1) as $b
| count( range(1; 1+$n) | select( . % $b == (.*.) % $b) ) / $n ;</langsyntaxhighlight>
For example:
 
Line 1,062 ⟶ 1,401:
 
produces:
<langsyntaxhighlight lang="sh">0.3
0.27
0.267
0.2667
0.26667</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">co9(x) = x == 9 ? 0 :
1<=x<=8 ? x :
co9(sum(digits(x)))</langsyntaxhighlight>
iskaprekar is defined in the task
[[Kaprekar_numbers#Julia]].
Line 1,083 ⟶ 1,421:
julia> show(filter(x->x%15 == (x^2)%15, 1:100)) # base 16
[1,6,10,15,16,21,25,30,31,36,40,45,46,51,55,60,61,66,70,75,76,81,85,90,91,96,100]</pre>
 
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun castOut(base: Int, start: Int, end: Int): List<Int> {
Line 1,110 ⟶ 1,447:
println()
println(castOut(17, 1, 288))
}</langsyntaxhighlight>
 
{{out}}
Line 1,120 ⟶ 1,457:
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]
</pre>
 
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">local N = 2
local base = 10
local c1 = 0
Line 1,137 ⟶ 1,473:
 
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.0 * c2 / c1))</langsyntaxhighlight>
{{out}}
<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Trying 22 numbers instead of 99 numbers saves 77.777778%</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Task 1: Simple referenced implementation that handles any base:
<langsyntaxhighlight lang="mathematica">Co9[n_, b_: 10] :=
With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]},
If[ans == b - 1, 0, ans]];</langsyntaxhighlight>
 
{{out|Task 1 output}}
<langsyntaxhighlight lang="mathematica">Co9 /@ (vals = {1235, 2345, 4753})
{2, 5, 1}
 
Total[Co9 /@ vals] == Co9[Total[vals]]
True</langsyntaxhighlight>
 
Task 2:
<langsyntaxhighlight lang="mathematica">task2 = Select[Range@100, Co9[#] == Co9[#^2] &] </langsyntaxhighlight>
 
{{out|Task 2 output}}
Line 1,165 ⟶ 1,500:
Task 3:
Defines the efficient co9 using Mod.
<langsyntaxhighlight lang="mathematica">Co9eff[n_, b_: 10] := Mod[n, b - 1]; </langsyntaxhighlight>
 
{{out|Task 3 output}}
Testing bases 10 and 17
<langsyntaxhighlight lang="mathematica">task2 == Select[Range@100, Co9eff[#] == Co9eff[#^2] &]
True
 
Select[Range@100, Co9eff[#, 17] == Co9eff[#^2, 17] &]
{1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils
 
iterator castOut(base = 10, start = 1, ending = 999_999): int =
Line 1,198 ⟶ 1,532:
inc x
 
echo toSeq(castOut(base=16, start=1, ending=255))</langsyntaxhighlight>
{{out}}
<pre>@[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class CastingNines {
function : Main(args : String[]) ~ Nil {
base := 10;
Line 1,222 ⟶ 1,555:
->As(Float)*100))->PrintLine("%");
}
}</langsyntaxhighlight>
 
{{out}}
<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Trying 22 numbers instead of 99 numbers saves 77.7777778%</pre>
 
=={{header|PARI/GP}}==
{{trans|C++}}
<langsyntaxhighlight lang="parigp">{base=10;
N=2;
c1=c2=0;
Line 1,241 ⟶ 1,573:
);
print("\nTrying "c2" numbers instead of "c1" numbers saves " 100.-(c2/c1)*100 "%")}
</syntaxhighlight>
</lang>
{{out|Produces}}
<pre>
Line 1,254 ⟶ 1,586:
255
Trying 68 numbers instead of 255 numbers saves 73.33333333333333333333333333%</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub co9 { # Follows the simple procedure asked for in Part 1
my $n = shift;
return $n if $n < 10;
Line 1,288 ⟶ 1,619:
printf "[@l]\nIn base %d, trying %d numbers instead of %d saves %.4f%%\n\n",
$base, $n, $N, 100-($n/$N)*100;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,304 ⟶ 1,635:
In base 17, trying 36 numbers instead of 288 saves 87.5000%
</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure co9(integer start, integer base, integer lim, sequence kaprekars)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer c1=0,
<span style="color: #008080;">procedure</span> <span style="color: #000000;">co9</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">kaprekars</span><span style="color: #0000FF;">)</span>
c2=0
<span style="color: #004080;">integer</span> <span style="color: #000000;">c1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
sequence s = {}
<span style="color: #000000;">c2</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
for k=start to lim do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
c1 += 1
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">start</span> <span style="color: #008080;">to</span> <span style="color: #000000;">lim</span> <span style="color: #008080;">do</span>
if mod(k,base-1)=mod(k*k,base-1) then
<span style="color: #000000;">c1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
c2 += 1
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)=</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">*</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
s &= k
<span style="color: #000000;">c2</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">k</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
string msg = "Valid subset\n"
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for i=1 to length(kaprekars) do
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"valid subset"</span>
if not find(kaprekars[i],s) then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">kaprekars</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
msg = "***INVALID***\n"
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">kaprekars</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
exit
<span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"***INVALID***"</span>
end if
<span style="color: #008080;">exit</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if length(s)>40 then s[20..-20] = {"..."} end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
?s
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)></span><span style="color: #000000;">25</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">10</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"..."</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
puts(1,"Kaprekar numbers:")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%V\nKaprekar numbers: %V - %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">kaprekars</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">})</span>
?kaprekars
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Trying %d numbers instead of %d saves %3.2f%%\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">c2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">-(</span><span style="color: #000000;">c2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">c1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span>
puts(1,msg)
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
printf(1,"Trying %d numbers instead of %d saves %3.2f%%\n\n",{c2,c1,100-(c2/c1)*100})
end procedure
<span style="color: #000000;">co9</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">99</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">,</span><span style="color: #000000;">55</span><span style="color: #0000FF;">,</span><span style="color: #000000;">99</span><span style="color: #0000FF;">})</span>
 
<span style="color: #000000;">co9</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0(17)10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">*</span><span style="color: #000000;">17</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0(17)3d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0(17)d4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0(17)gg</span><span style="color: #0000FF;">})</span>
co9(1, 10, 99, {1,9,45,55,99})
<span style="color: #000000;">co9</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1000</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">,</span><span style="color: #000000;">55</span><span style="color: #0000FF;">,</span><span style="color: #000000;">99</span><span style="color: #0000FF;">,</span><span style="color: #000000;">297</span><span style="color: #0000FF;">,</span><span style="color: #000000;">703</span><span style="color: #0000FF;">,</span><span style="color: #000000;">999</span><span style="color: #0000FF;">})</span>
co9(0(17)10, 17, 17*17, {0(17)3d,0(17)d4,0(17)gg})
<!--</syntaxhighlight>-->
co9(1, 10, 1000, {1,9,45,55,99,297,703,999})</lang>
{{out}}
<pre>
{1,9,10,18,19,27,28,36,37,45,46,54,55,63,64,72,73,81,82,90,91,99}
Kaprekar numbers: {1,9,45,55,99} - valid subset
Valid subset
Trying 22 numbers instead of 99 saves 77.78%
 
{17,32,33,48,49,64,65,80,81,96,97,112,113,128,129,144,145,160,161,176,177,192,193,208,209,224"...",225,240,241,256,257,272,273,288,289}
Kaprekar numbers: {64,225,288} - valid subset
Valid subset
Trying 35 numbers instead of 273 saves 87.18%
 
{1,9,10,18,19,27,28,36,37,45,46,54,55,63,64,72,73,81,82,"...",919,927,928,936,937,945,946,954,955,963,964,972,973,981,982,990,991,999,1000}
Kaprekar numbers: {1,9,45,55,99,297,703,999} - valid subset
Valid subset
Trying 223 numbers instead of 1000 saves 77.70%
</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Base10 = 10,
foreach(N in [2,6])
casting_out_nines(Base10,N)
end,
nl,
Base16 = 16,
foreach(N in [2,6])
casting_out_nines(Base16,N)
end,
nl.
 
casting_out_nines(Base,N) =>
println([base=Base,n=N]),
C1 = 0,
C2 = 0,
Ks = [],
LimitN = 3,
foreach(K in 1..Base**N-1)
C1 := C1 + 1,
if K mod (Base-1) == (K*K) mod (Base-1) then
C2 := C2+1,
if N <= LimitN then
Ks := Ks ++ [K]
end
end
end,
if C2 <= 100 then
println(ks=Ks)
end,
printf("Trying %d numbers instead of %d numbers saves %2.3f%%\n", C2, C1, 100 - ((C2/C1)*100)),
nl.</syntaxhighlight>
 
{{out}}
<pre>[base = 10,n = 2]
ks = [1,9,10,18,19,27,28,36,37,45,46,54,55,63,64,72,73,81,82,90,91,99]
Trying 22 numbers instead of 99 numbers saves 77.778%
 
[base = 10,n = 6]
Trying 222222 numbers instead of 999999 numbers saves 77.778%
 
[base = 16,n = 2]
ks = [1,6,10,15,16,21,25,30,31,36,40,45,46,51,55,60,61,66,70,75,76,81,85,90,91,96,100,105,106,111,115,120,121,126,130,135,136,141,145,150,151,156,160,165,166,171,175,180,181,186,190,195,196,201,205,210,211,216,220,225,226,231,235,240,241,246,250,255]
Trying 68 numbers instead of 255 numbers saves 73.333%
 
[base = 16,n = 6]
Trying 4473924 numbers instead of 16777215 numbers saves 73.333%</pre>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de kaprekar (N)
(let L (cons 0 (chop (* N N)))
(for ((I . R) (cdr L) R (cdr R))
Line 1,389 ⟶ 1,763:
(range 1 100) ) )
(bye)</langsyntaxhighlight>
 
{{out}}
Line 1,401 ⟶ 1,775:
(1 16 17 32 33 48 49 64 65 80 81 96 97)
</pre>
 
=={{header|Python}}==
This works slightly differently, generating the "wierd" (as defined by Counting Out Nines) numbers which may be Kaprekar, rather than filtering all numbers in a range.
<langsyntaxhighlight Pythonlang="python"># Casting out Nines
#
# Nigel Galloway: June 27th., 2012,
Line 1,422 ⟶ 1,795:
 
for V in CastOut(Base=16,Start=1,End=255):
print(V, end=' ')</langsyntaxhighlight>
Produces:
<pre>
Line 1,435 ⟶ 1,808:
1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288
</pre>
=={{header|Quackery}}==
 
<code>kaprekar</code> is defined at [[Kaprekar numbers#Quackery]].
 
<syntaxhighlight lang="quackery"> [ true unrot swap
witheach
[ over find
over found not if
[ dip not
conclude ] ]
drop ] is subset ( [ [ --> [ )
 
[ abs 0 swap
[ 10 /mod rot +
dup 8 > if [ 9 - ]
swap dup 0 = until ]
drop ] is co9 ( n --> n )
 
say "Part 1: Examples from Dr Math page." cr cr
say "6395 1259 + = " 6395 1259 + echo cr
say "6395 co9 = " 6395 co9 echo cr
say "1259 co9 = " 1259 co9 echo cr
say "5 8 + co9 = " 5 8 + co9 echo cr
say "7654 co9 = " 7654 co9 echo cr cr
say "6395 1259 * = " 6395 1259 * echo cr
say "6395 co9 = " 6395 co9 echo cr
say "1259 co9 = " 1259 co9 echo cr
say "5 8 * co9 = " 5 8 * co9 echo cr
say "8051305 co9 = " 7654 co9 echo cr cr
say "Part 2: Kaprekar numbers." cr cr
say "Kaprekar numbers less than one hundred: "
[]
100 times
[ i^ kaprekar if
[ i^ join ] ]
dup echo cr
say '0...99 with property "n co9 n 2 ** co9 =": '
[]
100 times
[ i^ co9
i^ 2 ** co9 = if
[ i^ join ] ]
dup echo cr
say "Is the former a subset of the latter? "
subset iff [ say "Yes." ] else [ say "No." ] cr cr
say "Part 3: Same as Part 2, but base 17." cr cr
say "Kaprekar (base 17) numbers less than one hundred: "
17 base put
[]
100 times
[ i^ kaprekar if
[ i^ join ] ]
base release
dup echo cr
say '0...99 with property "n 16 mod n 2 ** 16 mod =": '
[]
100 times
[ i^ 16 mod
i^ 2 ** 16 mod = if
[ i^ join ] ]
dup echo cr
say "Is the former a subset of the latter? "
subset iff [ say "Yes." ] else [ say "No." ]</syntaxhighlight>
 
{{out}}
 
<pre>Part 1: Examples from Dr Math page.
 
6395 1259 + = 7654
6395 co9 = 5
1259 co9 = 8
5 8 + co9 = 4
7654 co9 = 4
 
6395 1259 * = 8051305
6395 co9 = 5
1259 co9 = 8
5 8 * co9 = 4
8051305 co9 = 4
 
Part 2: Kaprekar numbers.
 
Kaprekar numbers less than one hundred: [ 1 9 45 55 99 ]
0...99 with property "n co9 n 2 ** co9 =": [ 0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 ]
Is the former a subset of the latter? Yes.
 
Part 3: Same as Part 2, but base 17.
 
Kaprekar (base 17) numbers less than one hundred: [ 1 16 64 ]
0...99 with property "n 16 mod n 2 ** 16 mod =": [ 0 1 16 17 32 33 48 49 64 65 80 81 96 97 ]
Is the former a subset of the latter? Yes.
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="R">
co9 <- function(base) {
x <- 1:(base^2-1)
x[(x %% (base-1)) == (x^2 %% (base-1))]
}
Map(co9,c(10,16,17))
</syntaxhighlight>
{{out}}
<pre>
[[1]]
[1] 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
 
[[2]]
[1] 1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96
[27] 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195
[53] 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255
 
[[3]]
[1] 1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208
[27] 209 224 225 240 241 256 257 272 273 288
</pre>
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(require math)
 
Line 1,447 ⟶ 1,939:
(with-modulus 9
(for/fold ([sum 0]) ([d (digits n)])
(mod+ sum d))))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Python}}
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>sub cast-out(\BASE = 10, \MIN = 1, \MAX = BASE**2 - 1) {
my \B9 = BASE - 1;
my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9);
Line 1,468 ⟶ 1,959:
say cast-out;
say cast-out 16;
say cast-out 17;</langsyntaxhighlight>
{{out}}
<pre>(1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99)
(1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255)
(1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288)</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates the casting─out─nines algorithm (with Kaprekar numbers). */
parse arg LO HI base . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then do; LO=1; HI=1000; end /*Not specified? Then use the default*/
Line 1,514 ⟶ 2,004:
end /*m*/ /* [↑] found a Kaprekar number. */
end /*j*/
return strip($) /*return Kaprekar numbers to invoker. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,538 ⟶ 2,028:
For 256 numbers, 69 passed the cast-out-15 test (26.95%) for base 16.
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Casting out nines
 
Line 1,578 ⟶ 2,067:
svect = left(svect, len(svect) - 2)
see svect + "}" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,592 ⟶ 2,081:
Valid subset
Trying 223 numbers instead of 1000 saves 77.70%
</pre>
=={{header|RPL}}==
====Task part 1: naive approach====
« '''WHILE''' DUP 9 > '''REPEAT'''
→STR 0
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB STR→ +
'''NEXT'''
SWAP DROP
'''END'''
» '<span style="color:blue">CO9</span>' STO <span style="color:grey">''@ ( n → remainder )''</span>
====Kaprekar number checker (any base)====
{{works with|RPL|HP48-R}}
« OVER SQ → n b n2
« 1 CF
1 n2 LN b LN / IP 1 + '''FOR''' j
n2 b j ^ MOD LASTARG / IP
'''IF''' OVER '''THEN'''
'''IF''' + n == '''THEN''' 1 SF n 'j' STO '''END'''
'''ELSE''' DROP2 '''END'''
'''NEXT'''
1 FS?
» » '<span style="color:blue">ISBKAR?</span>' STO <span style="color:grey">''@ ( n base → boolean )''</span>
====Task parts 2 & 3====
« { } → n base kaprekar
« 1 n '''FOR''' j
'''IF''' j base ISBKAR? '''THEN''' 'kaprekar' j STO+ '''END'''
'''NEXT'''
{ }
1 n '''FOR''' k
'''IF''' k base 1 - MOD LASTARG SWAP SQ SWAP MOD == '''THEN''' k + '''END'''
'''NEXT'''
0
1 kaprekar SIZE '''FOR''' j
'''IF''' OVER kaprekar j GET POS NOT '''THEN''' 1 + '''END'''
'''NEXT'''
"Missing K#" →TAG
1 3 PICK SIZE n / - "% saved" →TAG
» » '<span style="color:blue">CASTOUT</span>' STO <span style="color:grey">''@ ( span base → results )''</span>
 
255 10 <span style="color:blue">CASTOUT</span>
255 17 <span style="color:blue">CASTOUT</span>
{{out}}
<pre>
6: { 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 108 109 117 118 126 127 135 136 144 145 153 154 162 163 171 172 180 181 189 190 198 199 207 208 216 217 225 226 234 235 243 244 252 253 }
5: Missing K#:0
4: % saved: .776470588235
3: { 1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 }
2: Missing K#:0
1: % saved: .878431372549
</pre>
 
=={{header|Ruby}}==
{{trans|C}}
<langsyntaxhighlight lang="ruby">N = 2
base = 10
c1 = 0
Line 1,610 ⟶ 2,149:
 
puts
print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]</langsyntaxhighlight>
{{out}}
<pre>1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Line 1,616 ⟶ 2,155:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn compare_co9_efficiency(base: u64, upto: u64) {
let naive_candidates: Vec<u64> = (1u64..upto).collect();
let co9_candidates: Vec<u64> = naive_candidates.iter().cloned()
Line 1,636 ⟶ 2,175:
compare_co9_efficiency(10, 100);
compare_co9_efficiency(16, 256);
}</langsyntaxhighlight>
 
{{out}}
Line 1,643 ⟶ 2,182:
1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255
Trying 68 numbers instead of 255 saves 73.33%</pre>
 
=={{header|Scala}}==
Code written in scala follows functional paradigm of programming, finds list of candidates for Kaprekar numbers within given range.
<syntaxhighlight lang="scala">
<lang Scala>
object kaprekar{
// PART 1
Line 1,663 ⟶ 2,201:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,674 ⟶ 2,212:
List(993, 992, 977, 976, 961, 960, 945, 944, 929, 928, 913, 912, 897, 896, 881, 880, 865, 864, 849, 848, 833, 832, 817, 816, 801, 800, 785, 784, 769, 768, 753, 752, 737, 736, 721, 720, 705, 704, 689, 688, 673, 672, 657, 656, 641, 640, 625, 624, 609, 608, 593, 592, 577, 576, 561, 560, 545, 544, 529, 528, 513, 512, 497, 496, 481, 480, 465, 464, 449, 448, 433, 432, 417, 416, 401, 400, 385, 384, 369, 368, 353, 352, 337, 336, 321, 320, 305, 304, 289, 288, 273, 272, 257, 256, 241, 240, 225, 224, 209, 208, 193, 192, 177, 176, 161, 160, 145, 144, 129, 128, 113, 112, 97, 96, 81, 80, 65, 64, 49, 48, 33, 32, 17, 16)
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func bitset: castOut (in integer: base, in integer: start, in integer: ending) is func
Line 1,712 ⟶ 2,249:
begin
writeln(castOut(16, 1, 255));
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,718 ⟶ 2,255:
{1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255}
</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func cast_out(base = 10, min = 1, max = (base**2 - 1)) {
 
var b9 = base-1
Line 1,743 ⟶ 2,279:
say cast_out().join(' ')
say cast_out(16).join(' ')
say cast_out(17).join(' ')</langsyntaxhighlight>
{{out}}
<pre>
Line 1,750 ⟶ 2,286:
1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc co9 {x} {
while {[string length $x] > 1} {
set x [tcl::mathop::+ {*}[split $x ""]]
Line 1,790 ⟶ 2,325:
}
puts $satisfying
puts "Trying [llength $satisfying] numbers instead of 255 numbers saves [percent [llength $satisfying] 255]"</langsyntaxhighlight>
{{out}}With some newlines inserted…
<pre>
Line 1,802 ⟶ 2,337:
Trying 68 numbers instead of 255 numbers saves 73.33%
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|Java}}
<langsyntaxhighlight lang="vbnet">Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Line 1,846 ⟶ 2,380:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]
[1, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 63, 64, 72, 73, 81, 82, 90, 91, 99]
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]</pre>
 
=={{header|V (Vlang)}}==
{{trans|Kotlin}}
<syntaxhighlight lang="Zig">
fn main() {
println(cast_out(16, 1, 255))
println("")
println(cast_out(10, 1, 99))
println("")
println(cast_out(17, 1, 288))
}
 
fn cast_out(base int, start int, end int) []int {
b := []int{len: base - 1, init: index}
ran := b.filter(it % b.len == (it * it) % b.len)
mut x, mut k := start / b.len, 0
mut result := []int{}
for {
for n in ran {
k = b.len * x + n
if k < start {continue}
if k > end {return result}
result << k
}
x++
}
return result
}
</syntaxhighlight>
 
{{out}}
<pre>
[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]
 
[1, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 63, 64, 72, 73, 81, 82, 90, 91, 99]
 
[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]
</pre>
 
=={{header|Wren}}==
{{trans|D}}
<langsyntaxhighlight ecmascriptlang="wren">var castOut = Fn.new { |base, start, end|
var b = base - 1
var ran = (0...b).where { |n| n % b == (n * n) % b }
Line 1,875 ⟶ 2,447:
System.print(castOut.call(10, 1, 99))
System.print()
System.print(castOut.call(17, 1, 288))</langsyntaxhighlight>
 
{{out}}
Line 1,886 ⟶ 2,458:
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
<syntaxhighlight lang "XPL0">include xpllib;
 
def N = 2.;
int Base, C1, C2, K;
\int Main\ [
Base:= 10; C1:= 0; C2:= 0;
for K:= 1 to fix(Pow(float(Base), N)) - 1 do [
C1:= C1+1;
if rem(K/(Base-1)) = rem((K*K)/(Base-1)) then [
C2:= C2+1;
Print("%d ", K);
]
];
 
Print("\nTrying %d numbers instead of %d numbers saves %1f%%\n",
C2, C1, 100.0 - 100.0*float(C2)/float(C1));
return 0;
]</syntaxhighlight>
{{out}}
<pre>
1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99
Trying 22 numbers instead of 99 numbers saves 77.77778%
</pre>
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn castOut(base=10, start=1, end=999999){
base-=1;
ran:=(0).filter(base,'wrap(n){ n%base == (n*n)%base });
Line 1,899 ⟶ 2,496:
}
// doesn't get here
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">castOut(16, 1, 255).toString(*).println("\n-----");
castOut(10, 1, 99).toString(*).println("\n-----");
castOut(17, 1, 288).toString(*).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,916 ⟶ 2,513:
241,256,257,272,273,288)
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|C++}}
<langsyntaxhighlight lang="zxbasic">10 LET Base=10
20 LET N=2
30 LET c1=0
Line 1,932 ⟶ 2,528:
160 STOP
170 DEF FN m(a,b)=a-INT (a/b)*b
</syntaxhighlight>
</lang>
 
{{omit from|GUISS}}
3

edits