Kaprekar numbers: Difference between revisions

Added Easylang
m (added highlighting, added whitespace.)
(Added Easylang)
 
(26 intermediate revisions by 21 users not shown)
Line 47:
*   [[Casting out nines]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F k(n)
V n2 = String(Int64(n) ^ 2)
L(i) 0 .< n2.len
V a = I i > 0 {Int(n2[0 .< i])} E 0
V b = Int(n2[i ..])
I b != 0 & a + b == n
R 1B
R 0B
 
print((1..9999).filter(x -> k(x)))
print((1..999999).filter(x -> k(x)).len)</syntaxhighlight>
 
{{out}}
<pre>
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
54
</pre>
 
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Kaprekar numbers 22/03/ 2017
KAPREKAR CSECT
USING KAPREKAR,R13 base register
Line 144 ⟶ 165:
PG DC CL80' ' buffer
YREGS
END KAPREKAR</langsyntaxhighlight>
{{out}}
<pre>
Line 175 ⟶ 196:
so i chose base 17 (17 ** 6).
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Strings.Fixed;
 
Line 305 ⟶ 326:
end loop;
Ada.Text_IO.Put_Line (" Total:" & Integer'Image (Count));
end Kaprekar2;</langsyntaxhighlight>
 
{{out}}
Line 314 ⟶ 335:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># find some Kaprekar numbers #
 
# returns TRUE if n is a Kaprekar number, FALSE otherwise #
Line 357 ⟶ 378:
print( ( newline ) );
print( ( "There are ", whole( k count, 0 ), " Kaprekar numbers below ", whole( max number, 0 ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 364 ⟶ 385:
There are 54 Kaprekar numbers below 1000000
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">k?: function [n][
n2: to :string n*n
loop 0..dec size n2 'i [
a: (i > 0)? -> to :integer slice n2 0 dec i -> 0
b: to :integer slice n2 i dec size n2
if and? b > 0 n = a + b -> return true
]
return false
]
 
loop 1..10000 'x [
if k? x -> print x
]</syntaxhighlight>
 
{{out}}
 
<pre>1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999</pre>
 
=={{header|AutoHotkey}}==
Function:
<langsyntaxhighlight AutoHotkeylang="autohotkey">Kaprekar(L) {
Loop, % L + ( C := 0 ) {
S := ( N := A_Index ) ** 2
Line 381 ⟶ 438:
}
Return C " Kaprekar numbers in [1-" L "]:`n" SubStr(R,3)
}</langsyntaxhighlight>
Usage:
<syntaxhighlight lang AutoHotkey="autohotkey">MsgBox, % Kaprekar(10000)</langsyntaxhighlight>
{{out}}
<pre>17 Kaprekar numbers in [1-10000]:
Line 389 ⟶ 446:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KAPREKAR_NUMBERS.AWK
BEGIN {
Line 415 ⟶ 472:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 439 ⟶ 496:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 498 ⟶ 555:
set /a tempcount+=1
goto lengthloop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 520 ⟶ 577:
</pre>
 
=={{header|BBC BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">n = 0
for i = 1 to 1999999
if Kaprekar(i) then
n = n + 1
if i < 100001 then print n; ": "; i
endif
next i
print
print "Total de números de Kaprekar por debajo de 1.000.000 = "; n
end
 
function Kaprekar(n)
s = n ^ 2
t = 10 ^ (int(log(s)) + 1)
do
t = t / 10
if t <= n then exit do #break
if s-n = int(s/t)*(t-1) then return TRUE
until t <= n
return n = 1
end function</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
n% = 0
FOR i% = 1 TO 999999
Line 542 ⟶ 623:
IF s-n = INT(s/t)*(t-1) THEN = TRUE
UNTIL FALSE
= (n=1)</langsyntaxhighlight>
{{out}}
<pre>
Line 573 ⟶ 654:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( 0:?n
& 1:?count
& out$(!count 1)
Line 590 ⟶ 671:
)
& out$(str$("There are " !count " kaprekar numbers less than 1000000"))
);</langsyntaxhighlight>
{{out}}
<pre>1 1
Line 612 ⟶ 693:
 
=={{header|Brat}}==
<langsyntaxhighlight Bratlang="brat">kaprekar = { limit |
results = []
 
Line 638 ⟶ 719:
 
p "Number of Kaprekar numbers below 1,000,000:"
p kaprekar(1000000).length</langsyntaxhighlight>
 
{{out}}
Line 650 ⟶ 731:
=={{header|C}}==
Sample for extra extra credit:
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
Line 708 ⟶ 789:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>base 10:
Line 757 ⟶ 838:
===Factorization===
Kaprekar numbers for base <math>b</math> can be directly generated by factorization of <math>b^n - 1</math> and multiplicative inverse of its unitary divisors. The speed largely depends on how easy the factorization part is, though it's not a problem for relatively small numbers (up to 32-bits, for example).
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 860 ⟶ 941:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 925 ⟶ 1,006:
}
 
}</langsyntaxhighlight>
 
{{out}}
Line 986 ⟶ 1,067:
=={{header|C++}}==
===Using String Manipulation (very slow)===
<langsyntaxhighlight lang="cpp">#include <vector>
#include <string>
#include <iostream>
Line 1,039 ⟶ 1,120:
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers up to 10000:
Line 1,073 ⟶ 1,154:
The code <code>"if ((k*(k-1))%(Base-1) == 0)"</code> is explained here: [[Casting out nines]].
 
<langsyntaxhighlight lang="cpp">
// Generate Kaperkar Numbers
//
Line 1,096 ⟶ 1,177:
return 0;
}
</syntaxhighlight>
</lang>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,153 ⟶ 1,234:
54: 999999 is 999998 + 1 and squared is 999998000001. It is a member of Residual Set 0</pre>
The code may be modified to use a base other than 10:
<langsyntaxhighlight lang="cpp">
const int Base = 16;
const int N = 4;
std::cout << std::dec << ++Paddy_cnt << ": " << std::hex << k << " is " << q << " + " << (int)nr << " and squared is " << k*k << ". It is a member of Residual Set " << k%(Base-1) << "\n";
</syntaxhighlight>
</lang>
Which produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,202 ⟶ 1,283:
===Casting Out Nines C++11 For Each Generator (v.fast)===
For details of ran and co9 see: http://rosettacode.org/wiki/Casting_out_nines#C.2B.2B11_For_Each_Generator
<langsyntaxhighlight lang="cpp">// Generate Kaprekar Numbers using Casting Out Nines Generator
//
// Nigel Galloway. July 13th., 2012
Line 1,216 ⟶ 1,297:
const double nr = k*(B-k)/(B-1);
const int q = k-nr;
if ((k*k==q*B+nr && 0<nr)) {
std::cout << ++Paddy_cnt << ": " << k << " is " << q << " + " << (int)nr << " and squared is " << k*k << ". It is a member of Residual Set " << k%(r.base-1) << "\n";
}}
return 0;
}</langsyntaxhighlight>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,277 ⟶ 1,358:
54: 999999 is 999998 + 1 and squared is 999998000001. It is a member of Residual Set 0</pre>
Changing main:
<langsyntaxhighlight lang="cpp">
const ran r = ran(16);
std::cout << std::dec << ++Paddy_cnt << ": " << std::hex << k << " is " << q << " + " << (int)nr << " and squared is " << k*k << ". It is a member of Residual Set " << k%(r.base-1) << "\n";
</syntaxhighlight>
</lang>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,323 ⟶ 1,404:
40: e6e6 is d042 + 16a4 and squared is d04216a4. It is a member of Residual Set a
41: ffff is fffe + 1 and squared is fffe0001. It is a member of Residual Set 0</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program assumes a 64-bit system.
% On a 32-bit system, the main task (show Kaprekar numbers < 10,000)
% will run correctly, but the extra credit part will crash with
% an overflow exception.
 
% Yield all positive splits of a number
splits = iter (n, base: int) yields (int,int)
step: int := base
while n >= step do
left: int := n / step
right: int := n // step
if left ~= 0 & right ~= 0 then
yield(left, right)
end
step := step * base
end
end splits
 
% Check whether a number is a Kaprekar number, and if so,
% return the proper split.
kap_split = struct[left, right: int]
maybe_kap = oneof[yes: kap_split, no: null]
kaprekar = proc (n, base: int) returns (maybe_kap)
for left, right: int in splits(n**2, base) do
if left + right = n then
return(maybe_kap$make_yes(
kap_split${left:left, right:right}))
end
end
return(maybe_kap$make_no(nil))
end kaprekar
 
% Format a number in a given base
to_base = proc (n, base: int) returns (string)
own digits: string := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n=0 then return("0") end
ds: array[char] := array[char]$[]
while n>0 do
array[char]$addl(ds,digits[n // base + 1])
n := n / base
end
return(string$ac2s(ds))
end to_base
 
% If a number is a Kaprekar number, show it, its square, and the split
display = proc (o: stream, n, base: int)
tagcase kaprekar(n, base)
tag yes (s: kap_split):
stream$putright(o, to_base(n, 10), 6)
if base ~= 10 then
stream$putright(o, to_base(n, base), 7)
end
stream$putright(o, to_base(n**2, base), 13)
stream$putl(o, " " ||
to_base(s.left, base) || " + " ||
to_base(s.right, base))
tag no:
end
end display
 
start_up = proc ()
po: stream := stream$primary_output()
% Find and output all the Kaprekar numbers under 10,000.
stream$putl(po, "Kaprekar numbers < 10,000:")
for i: int in int$from_to(1, 9999) do
display(po, i, 10)
end
% Count all the Kaprekar numbers under 1,000,000.
kaps: int := 0
for i: int in int$from_to(1, 999999) do
tagcase kaprekar(i, 10)
tag yes (s: kap_split): kaps := kaps + 1
tag no:
end
end
stream$putl(po, "\nThere are " || int$unparse(kaps) ||
" Kaprekar numbers under 1,000,000.\n")
% Find and output all base-17 Kaprekar numbers under 1,000,000.
stream$putl(po, "Base-17 Kaprekar numbers < 1,000,000:")
for i: int in int$from_to(1, 999999) do
display(po, i, 17)
end
end start_up</syntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10,000:
9 81 8 + 1
45 2025 20 + 25
55 3025 30 + 25
99 9801 98 + 1
297 88209 88 + 209
703 494209 494 + 209
999 998001 998 + 1
2223 4941729 494 + 1729
2728 7441984 744 + 1984
4879 23804641 238 + 4641
4950 24502500 2450 + 2500
5050 25502500 2550 + 2500
5292 28005264 28 + 5264
7272 52881984 5288 + 1984
7777 60481729 6048 + 1729
9999 99980001 9998 + 1
 
There are 53 Kaprekar numbers under 1,000,000.
 
Base-17 Kaprekar numbers < 1,000,000:
16 G F1 F + 1
64 3D E2G E + 2G
225 D4 A52G A5 + 2G
288 GG GF01 GF + 1
1536 556 1B43B2 1B4 + 3B2
3377 BBB 8093B2 809 + 3B2
4912 GGG GGF001 GGF + 1
7425 18BD 24E166G 24E + 166G
9280 1F1F 39B1B94 39B + 1B94
16705 36DB B992C42 B99 + 2C42
20736 43CD 10DE32FG 10DE + 32FG
30016 61EB 23593F92 2359 + 3F92
36801 785D 351E433G 351E + 433G
37440 7A96 37144382 3714 + 4382
46081 967B 52G94382 52G9 + 4382
46720 98B4 5575433G 5575 + 433G
53505 AF26 6GA43F92 6GA4 + 3F92
62785 CD44 9A5532FG 9A55 + 32FG
66816 DA36 AEG42C42 AEG4 + 2C42
74241 F1F2 D75F1B94 D75F + 1B94
76096 F854 E1F5166G E1F5 + 166G
83520 GGGG GGGF0001 GGGF + 1
266224 33334 A2C52A07G A2C5 + 2A07G</pre>
 
=={{header|CoffeeScript}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="coffeescript">splitAt = (str, idx) ->
ans = [ str.substring(0, idx), str.substring(idx) ]
if ans[0] == ""
Line 1,354 ⟶ 1,568:
console.log i, i.toString(base), s, p.join '+'
count++
console.log "#{count} Kaprekar numbers < #{max} (base 10) in base #{base}"</langsyntaxhighlight>
{{out}}
<pre>1 '1' '1' '0+1'
Line 1,370 ⟶ 1,584:
=={{header|Common Lisp}}==
=== Fast solution using casting out nines filter ===
<langsyntaxhighlight lang="lisp">;; make an infinite list whose accumulated sums give all
;; numbers n where n mod (base - 1) == n^2 mod (base - 1)
(defun res-list (base)
Line 1,411 ⟶ 1,625:
(terpri)
(ktest 1000000 17)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,435 ⟶ 1,649:
</pre>
===In the style of the C++ generator===
<langsyntaxhighlight lang="lisp">
;; Generate Kaprekar Numbers using Casting Out Nines Generator
;;
Line 1,450 ⟶ 1,664:
(format t "~3d: ~8d is ~8d + ~8d and squared is ~8d~&" (incf Paddy_cnt) N q nr kk))
(if (> B kk) (return)))))))))))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,597 ⟶ 1,811:
=={{header|D}}==
===Straightforward Version===
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.range;
 
bool isKaprekar(in long n) pure /*nothrow*/ @safe
Line 1,620 ⟶ 1,834:
iota(1, 10_000).filter!isKaprekar.writeln;
iota(1, 1_000_000).count!isKaprekar.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 1,627 ⟶ 1,841:
===Faster Version===
Right to left:
<langsyntaxhighlight lang="d">bool isKaprekar(in uint n) pure nothrow @nogc @safe {
ulong powr = n ^^ 2UL;
ulong r, l, tens = 10;
Line 1,647 ⟶ 1,861:
if (i.isKaprekar)
writefln("%d: %d", count++, i);
}</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 1,671 ⟶ 1,885:
53: 994708
54: 999999</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
function IsKaprekar(N: integer): boolean;
{Return true if N is a Kaperkar number}
var S,S1,S2: string;
var N1,N2,Sum: cardinal;
var Sp: integer;
begin
Result:=True;
if N=1 then exit;
{Convert N^2 to string}
S:=IntToStr(N * N);
{Try all different splits}
for Sp:=2 to Length(S) do
begin
{Split into two strings}
S1:=Copy(S,1,Sp-1);
S2:=Copy(S,Sp,(Length(S)-Sp)+1);
{Convert to integers}
N1:=StrToInt(S1);
N2:=StrToInt(S2);
{Zeros aren't allowed}
if (N1=0) or (N2=0) then continue;
{Test if sum matches original number}
Sum:=N1 + N2;
if Sum=N then exit;
end;
Result:=False;
end;
 
 
procedure ShowKaprekarNumbers(Memo: TMemo);
{Find all Kaprekar numbers less than 10,000}
var S: string;
var I: integer;
begin
for I:=1 to 10000 do
begin
if IsKaprekar(I) then Memo.Lines.Add(IntToStr(I));
end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999
</pre>
 
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
import 'dart:math';
void main()
Line 1,725 ⟶ 2,011:
 
 
</syntaxhighlight>
</lang>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func karp n .
h = n * n
e = 1
while h > 0
t += h mod 10 * e
e = e * 10
h = h div 10
if t > 0 and h + t = n
return 1
.
.
.
for i to 9999
if karp i = 1
write i & " "
.
.
</syntaxhighlight>
{{out}}
<pre>
1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule KaprekarNumber do
def check(n), do: check(n, 10)
Line 1,772 ⟶ 2,083:
:io.fwrite "~7w ~5s ~9s ~s + ~s~n", [n, Integer.to_string(n,base), a<>b, a, b]
end
end)</langsyntaxhighlight>
 
{{out}}
Line 1,823 ⟶ 2,134:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-mode(compile).
-import(lists, [seq/2]).
Line 1,851 ⟶ 2,162:
CountTo1e6 = length(Numbers) + length([N || N <- seq(10001, 999999), kaprekar(N)]),
io:format("There are ~p Kaprekar numbers < 1,000,000", [CountTo1e6]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,862 ⟶ 2,173:
{{incorrect|Euler Math Toolbox|4950 and 5050 are missing because j=0 should not return in the loop.}}
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function map kaprekarp (n) ...
$ m=n*n;
Line 1,879 ⟶ 2,190:
[ 1 9 45 55 99 297 703 999 2223 2728 4879 5292 7272 7777
9999 17344 22222 38962 77778 82656 95121 99999 ]
</syntaxhighlight>
</lang>
 
=={{header|F Sharp}}==
 
<syntaxhighlight lang="f sharp">
<lang F Sharp>
// Count digits in number
let digits x =
Line 1,919 ⟶ 2,230:
[1 .. 10000]
|> List.filter (float >> isKaprekar)
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
This solution is based on the following Haskell code: [https://dev.to/heikodudzus/comment/1cl6].
<langsyntaxhighlight lang="factor">USING: io kernel lists lists.lazy locals math math.functions
math.ranges prettyprint sequences ;
 
Line 1,937 ⟶ 2,248:
 
1,000,000 [1,b] [ kaprekar? ] filter dup . length
"Count of Kaprekar numbers <= 1,000,000: " write .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,970 ⟶ 2,281:
=={{header|Forth}}==
This one takes the internal Forth variable BASE into account. Since Forth is perfectly suited to work with any base between 2 and 36, this works just fine.
<langsyntaxhighlight lang="forth">: square ( n - n^2) dup * ;
 
\ Return nonzero if n is a Kaprekar number for tens, where tens is a
Line 1,988 ⟶ 2,299:
repeat
r> drop 1 = and ;
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Karpekar_Numbers
implicit none
Line 2,029 ⟶ 2,340:
if (printnums .eqv. .false.) write(*, "(i0)") c
end subroutine
end program</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,052 ⟶ 2,363:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-12-2016
' compile with: fbc -s console
 
Line 2,116 ⟶ 2,427:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 2,138 ⟶ 2,449:
 
54 numbers below 1000000 are Kaprekar numbers</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">isKaprekar[n, base=10] :=
{
if n==1
return [1, 1, 1]
 
s = base[n^2, base]
for i=1 to length[s]-1
{
ls = left[s,i]
l = parseInt[ls, base]
rs = right[s,-i]
r = parseInt[rs, base]
if isPositive[l] and isPositive[r] and l+r == n
return [n, s, "$ls + $rs"]
}
 
return undef
}
 
f = {|x| isKaprekar[x] != undef}
println[formatTable[select[1 to 9999, f], "right"]]
 
println[]
print[length[select[1 to 999_999, f]]]
println[" Kaprekar numbers less than 1,000,000"]
 
println["\nKaprekar numbers in base 17:"]
results = new array
for i = 1 to 999_999
{
r = isKaprekar[i, 17]
if r != undef
results.push[r]
}
println[formatTable[results, "right"]]</syntaxhighlight>
{{out}}
<pre>
1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999
 
54 Kaprekar numbers less than 1,000,000
 
Kaprekar numbers in base 17:
1 1 1
16 f1 f + 1
64 e2g e + 2g
225 a52g a5 + 2g
288 gf01 gf + 01
1536 1b43b2 1b4 + 3b2
3377 8093b2 809 + 3b2
4912 ggf001 ggf + 001
7425 24e166g 24e + 166g
9280 39b1b94 39b + 1b94
16705 b992c42 b99 + 2c42
20736 10de32fg 10de + 32fg
30016 23593f92 2359 + 3f92
36801 351e433g 351e + 433g
37440 37144382 3714 + 4382
46081 52g94382 52g9 + 4382
46720 5575433g 5575 + 433g
53505 6ga43f92 6ga4 + 3f92
62785 9a5532fg 9a55 + 32fg
66816 aeg42c42 aeg4 + 2c42
74241 d75f1b94 d75f + 1b94
76096 e1f5166g e1f5 + 166g
83520 gggf0001 gggf + 0001
266224 a2c52a07g a2c5 + 2a07g
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn kaprekar( n as NSInteger ) as BOOL
NSInteger s = n^2
double t = 10^(int(log(s)) + 1)
BOOL result = NO
do
t = t / 10
if t <= n then break
if s - n == int(s/t)*(t-1) then result = YES : exit fn
until ( t <= n )
result = ( n = YES )
end fn = result
 
local fn DoIt
NSInteger i
float n = 0
for i = 1 to 1000000
if ( fn kaprekar(i) )
n++
if i < 1000000 then printf @"%2.f : %ld", n, i
end if
next
print "Kaprekar numbers under 1,000,000 = "; n
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
1 : 1
2 : 9
3 : 45
4 : 55
5 : 99
6 : 297
7 : 703
8 : 999
9 : 2223
10 : 2728
11 : 4879
12 : 4950
13 : 5050
14 : 5292
15 : 7272
16 : 7777
17 : 9999
18 : 17344
19 : 22222
20 : 38962
21 : 77778
22 : 82656
23 : 95121
24 : 99999
25 : 142857
26 : 148149
27 : 181819
28 : 187110
29 : 208495
30 : 318682
31 : 329967
32 : 351352
33 : 356643
34 : 390313
35 : 461539
36 : 466830
37 : 499500
38 : 500500
39 : 533170
40 : 538461
41 : 609687
42 : 627615
43 : 643357
44 : 648648
45 : 670033
46 : 681318
47 : 791505
48 : 812890
49 : 818181
50 : 851851
51 : 857143
52 : 961038
53 : 994708
54 : 999999
Kaprekar numbers under 1,000,000 = �54
</pre>
 
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">IsKaprekar := function(n)
local a, b, p, q;
if n = 1 then
Line 2,250 ⟶ 2,739:
# 76096(10) or in base 17, F854^2 = E1F5166G and E1F5 + 166G = F854
# 83520(10) or in base 17, GGGG^2 = GGGF0001 and GGGF + 1 = GGGG
# 266224(10) or in base 17, 33334^2 = A2C52A07G and A2C5 + 2A07G = 33334</langsyntaxhighlight>
 
=={{header|Go}}==
Using the Ada interpretation of 1000000 base 17:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,327 ⟶ 2,816:
str, sq, sq[:split], sq[split:]) // optional extra extra credit
}
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10000:
Line 2,412 ⟶ 2,901:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class Kaprekar {
private static String[] splitAt(String str, int idx) {
String[] ans = new String[2]
Line 2,442 ⟶ 2,931:
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base " + base)
}
}</langsyntaxhighlight>
{{out}}
<pre>1 1 1 0 + 1
Line 2,501 ⟶ 2,990:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Text.Printf (printf)
import Data.Maybe (mapMaybe)
import Numeric (showIntAtBase)
Line 2,542 ⟶ 3,031:
putStrLn ""
putStrLn $ heading 17
mapM_ (putStrLn . printKap 17) $ zip [1 ..] (kaprekars 17 1000000)</langsyntaxhighlight>
{{out}}
<pre> # Value (base 10) Sum (base 10) Square
Line 2,596 ⟶ 3,085:
 
Generating Kaprekar numbers by factorizing b^n - 1:
<langsyntaxhighlight lang="haskell">import Control.Monad (foldM, join)
import Data.List (group, nub, sort)
 
Line 2,645 ⟶ 3,134:
 
main :: IO ()
main = mapM_ print $ kaprekars 10 10000000</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
<langsyntaxhighlight Iconlang="icon">procedure is_kaprekar(n) #: return n if n is a kaprekar number
if ( n = 1 ) |
( n^2 ? ( n = move(1 to *&subject-1) + (0 ~= tab(0)) | fail )) then
Line 2,659 ⟶ 3,148:
every (count := 0, is_kaprekar(1 to 999999), count +:= 1) # stretch goal
write ("Number of Kaprekar numbers less than 1000000 is ", count)
end</langsyntaxhighlight>
 
{{out}}
Line 2,683 ⟶ 3,172:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">kapbase=: 0,. [ ^ 1 + [: i. 1 + [ <.@^. >.&1
isKap=: 1 e. ] ((0 < {:"1@]) *. [ = +/"1@]) kapbase #: *:@]</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> I. 10 isKap"0 i.1e6
1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999 17344 22222 38962 77778 82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643 390313 461539 466830 499500 500500 533170 538461 609687 627615 643357 648648 670033 681318 791505 812890 818181 851851 857143 961038 994708 999999</langsyntaxhighlight>
 
"Extra credit": (text representing numbers left in boxes for alignment purposes)
<syntaxhighlight lang="j">
<lang j>
]K17=: I. 17 isKap"0 i.1e6
1 16 64 225 288 1536 3377 4912 7425 9280 16705 20736 30016 36801 37440 46081 46720 53505 62785 66816 74241 76096 83520 266224
Line 2,745 ⟶ 3,234:
├─────┼─────────┼─────┤
│33334│a2c52a07g│2a07g│
└─────┴─────────┴─────┘</langsyntaxhighlight>
 
The fastest times can be obtained by two optimizations: first, partitions with over half of the digits on the left (i.e. more than 3 for a 5-digit number) will not be considered because the left half is mathematically guaranteed to be greater than the original number in this case. Second, the numbers are computed in groups corresponding to the number of digits in their squares to allow isKap to be computed at full rank. Note that this method excludes 1, so it must be added manually to the list of solutions.
<langsyntaxhighlight lang="j"> kapbase=: 0,.10 ^ [: (<.+i.@>.)@(-:&.<:) 10 <.@^. >.&1
isKapGroup=: [: +./"1 (((0 < {:"1@]) *. [ = +/"1@]) (kapbase@{: #:"2 0 ])@:*:)
6!:2 'a=.1, I. ([:; (<@isKapGroup/.~ 10<.@^.*:)) i.1e6'
12.3963
#a
54</langsyntaxhighlight>
 
'''Alternative solution:'''
The following is a more naive, mechanical solution
<langsyntaxhighlight lang="j">splitNum=: {. ,&(_&".) }.
allSplits=: (i.&.<:@# splitNum"0 1 ])@":
sumValidSplits=: +/"1@:(#~ 0 -.@e."1 ])
filterKaprekar=: #~ ] e."0 1 [: sumValidSplits@allSplits"0 *:</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="j"> filterKaprekar i. 10000
0 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
#filterKaprekar i. 1e6
54</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
Line 2,799 ⟶ 3,288:
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}</langsyntaxhighlight>
{{out}} (base 10, shortened):
<pre>1 1 1 0 + 1
Line 2,845 ⟶ 3,334:
=={{header|JavaScript}}==
'''This string version'''
<langsyntaxhighlight JavaScriptlang="javascript">function isKaprekar( n, bs ) {
if ( n < 1 ) return false
if ( n == 1 ) return true
Line 2,856 ⟶ 3,345:
}
return false
}</langsyntaxhighlight>
'''or this numeric version'''
<langsyntaxhighlight JavaScriptlang="javascript">function isKaprekar( n, bs ) {
if ( n < 1 ) return false
if ( n == 1 ) return true
Line 2,868 ⟶ 3,357:
}
return false
}</langsyntaxhighlight>
'''with'''
<langsyntaxhighlight JavaScriptlang="javascript">function kaprekar( s, e, bs, pbs ) {
bs = bs || 10; pbs = pbs || 10
const toString = n => n.toString(pbs).toUpperCase()
Line 2,881 ⟶ 3,370:
kaprekar( 1, 255, 16)
kaprekar( 1, 255, 16, 16)
kaprekar( 1, 288, 17, 17)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,903 ⟶ 3,392:
=={{header|jq}}==
{{Works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># Is the input integer a Kaprekar integer?
def is_kaprekar:
# The helper function acts like a loop:
Line 2,934 ⟶ 3,423:
[ range(1;10000) | select( is_kaprekar ) ],
count( range(1;1000000); is_kaprekar )
;</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f is_kaprekar.jq
[1,9,45,55,99,297,703,999,2223,2728,4879,4950,5050,5292,7272,7777,9999]
54</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.2}}
 
<langsyntaxhighlight lang="julia">function iskaprekar(n::Integer)
n == 1 && return true
test(a, b) = n == a + b && b ≠ 0
Line 2,951 ⟶ 3,440:
 
@show filter(iskaprekar, 1:10000)
@show count(iskaprekar, 1:10000)</langsyntaxhighlight>
 
{{out}}
Line 2,959 ⟶ 3,448:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.lang.Long.parseLong
import java.lang.Long.toString
 
Line 2,993 ⟶ 3,482:
}
println("$count Kaprekar numbers < $max (base 10) in base $base")
}</langsyntaxhighlight>
{{out}}
<pre> 1 1 1 0 + 1
Line 3,052 ⟶ 3,541:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
For i = 1 To 10000 '1000000 - Changing to one million takes a long time to complete!!!!
Line 3,071 ⟶ 3,560:
Next i
End Function
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return length of an integer without string conversion
function numLength (n)
local length = 0
Line 3,106 ⟶ 3,595:
if isKaprekar(n) then count = count + 1 end
end
print("\nThere are " .. count .. " Kaprekar numbers under one million.")</langsyntaxhighlight>
{{out}}
<pre>1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
Line 3,114 ⟶ 3,603:
For a number x to be Kaprekar, it must have x^2 congruent to x mod 9.
Which is only achievable when x has remainder 1 or 0 mod 9. So we only check for these cases.
<syntaxhighlight lang="maple">
<lang Maple>
isKaprekar := proc(n::posint)
local holder, square, num_of_digits, k, left, right;
Line 3,140 ⟶ 3,629:
 
showKaprekar(10000);
countKaprekar(1000000);</langsyntaxhighlight>
 
{{out}}
Line 3,146 ⟶ 3,635:
54</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">KaprekaQ[1] = True;
KaprekaQ[n_Integer] := Block[{data = IntegerDigits[n^2], last = False, i = 1},
While[i < Length[data] && FromDigits[data[[i + 1 ;;]]] =!= 0 && Not[last],
last = FromDigits[data[[;; i]]] + FromDigits[data[[i + 1 ;;]]] == n;
i++]; last];
 
Select[Range[10000], KaprekaQ]
Length[Select[Range[1000000], KaprekaQ]]</syntaxhighlight>
 
Length[Select[Range[1000000], KaprekaQ]]</lang>
 
{{out}}
<pre>{1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999}
 
54</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">kaprekarp(n) := block(
[p, q, a, b],
if n = 1 then true else (
Line 3,187 ⟶ 3,672:
 
length(%);
54</langsyntaxhighlight>
 
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">local
val base = 10;
fun kaprekar
Line 3,225 ⟶ 3,710:
| (num :: nums) = kaprekar_list (num :: nums, [])
end
;</langsyntaxhighlight>
Generate and show all Kaprekar numbers less than 10,000.
<langsyntaxhighlight lang="ocaml">print "kaprekar numbers < 10_000: "; println ` kaprekar_list (iota 10000);</langsyntaxhighlight>
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
<langsyntaxhighlight lang="ocaml">print "number of kaprekar numbers < 1_000_000: "; println ` len ` kaprekar_list (iota 1000000);</langsyntaxhighlight>
Output:
<pre>kaprekar numbers < 10_000: [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 3,235 ⟶ 3,720:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Kaprekar;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
Line 3,297 ⟶ 3,782:
 
ReadChar
END Kaprekar.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils, sequtils
 
proc k(n: int): bool =
let n2 = $(n.in64int64 * n)
for i in 0 .. <n2.lenhigh:
let a = if i > 0: parseBiggestInt n2[0 .. < i] else: 0
let b = parseBiggestInt n2[i .. n2.high]
if b > 0 and a + b == n:
return true
 
echo toSeq(1..10_000).filter(k)
echo len toSeq(1..1_000_000).filter(k)</langsyntaxhighlight>
 
{{out}}
<pre>[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 3,317 ⟶ 3,803:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">K(d)={
my(D=10^d,DD,t,v=List());
for(n=D/10+1,D-1,
Line 3,338 ⟶ 3,824:
upTo(4)
v=upTo(6);v
#v</langsyntaxhighlight>
{{out}}
<pre>%1 = [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 3,348 ⟶ 3,834:
=={{header|Perl}}==
===Numeric with casting out nines (fast)===
<langsyntaxhighlight Perllang="perl">sub isKap {
my $k = shift;
return if $k*($k-1) % 9; # Fast return "casting out nines"
Line 3,364 ⟶ 3,850:
my @kaprekar;
isKap($_) && push @kaprekar,$_ for 1..1_000_000;
print "Kaprekar Numbers below 1000000: ", scalar(@kaprekar), "\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 3,375 ⟶ 3,861:
We can also use the method of [https://cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html Douglas Iannucci] to get much faster results (the below takes only a few milliseconds). This works for bigints as well.
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/fordivisors gcd invmod/;
 
my %kap;
Line 3,391 ⟶ 3,877:
printf "Kaprekar numbers <= 10^%2d: %5d\n",
$n, scalar(grep { $_ <= $np } @kap);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,406 ⟶ 3,892:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>atom r, l
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
function Kaprekar(integer n, base=10)
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span>
atom sq=n*n, basen = base
<span style="color: #008080;">function</span> <span style="color: #000000;">Kaprekar</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
if n=1 then return true end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">true</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
r=0
<span style="color: #004080;">atom</span> <span style="color: #000000;">sq</span><span style="color: #0000FF;">=</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">basen</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">base</span>
while r<n do
<span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
r = mod(sq,basen)
<span style="color: #008080;">while</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
l = floor(sq/basen)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">,</span><span style="color: #000000;">basen</span><span style="color: #0000FF;">)</span>
if r and l and l+r=n then return true end if
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sq</span><span style="color: #0000FF;">/</span><span style="color: #000000;">basen</span><span style="color: #0000FF;">)</span>
basen *= base
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span> <span style="color: #008080;">and</span> <span style="color: #000000;">l</span> <span style="color: #008080;">and</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">true</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">basen</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">base</span>
return false
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence s = {}
for i=1 to 10000 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
if Kaprekar(i) 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: #000000;">10_000</span> <span style="color: #008080;">do</span>
s &= i
<span style="color: #008080;">if</span> <span style="color: #000000;">Kaprekar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"There are %d Kaprekar numbers between 1 and 10,000:\n",length(s))
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
?s
<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;">"There are %d Kaprekar numbers between 1 and 10,000:\n%v\n"</span><span style="color: #0000FF;">,{</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;">s</span><span style="color: #0000FF;">})</span>
integer c = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to 1000000 do
<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: #000000;">1_000_000</span> <span style="color: #008080;">do</span>
c += Kaprekar(i)
<span style="color: #000000;">c</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">Kaprekar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"There are %d Kaprekar numbers between 1 and 1,000,000\n",c)
<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;">"There are %d Kaprekar numbers between 1 and 1,000,000\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
 
function base17(sequence s)
<span style="color: #008080;">function</span> <span style="color: #000000;">base17</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
atom si = s[i]
<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;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string num = ""
<span style="color: #004080;">atom</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
while si do
<span style="color: #004080;">string</span> <span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
integer digit = mod(si,17)
<span style="color: #008080;">while</span> <span style="color: #000000;">si</span> <span style="color: #008080;">do</span>
si = floor(si/17)
<span style="color: #004080;">integer</span> <span style="color: #000000;">digit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">)</span>
num = digit+iff(digit<=9?'0':87)&num
<span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">/</span><span style="color: #000000;">17</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">digit</span><span style="color: #0000FF;">+</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digit</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">9</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #000000;">87</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">num</span>
s[i] = num
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">num</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
s = {} r = 1 l = 1
for i=1 to 1000000 do
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if Kaprekar(i,17) 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: #000000;">1_000_000</span> <span style="color: #008080;">do</span>
s = append(s,{i,i*i,l,r})
<span style="color: #008080;">if</span> <span style="color: #000000;">Kaprekar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"There are %d Kaprekar base 17 numbers between 1 and 1,000,000 (decimal):\n",length(s))
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
s[5..-5] = {}
<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;">"There are %d Kaprekar base 17 numbers between 1 and 1,000,000 (decimal):\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
for i=1 to length(s) do
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
printf(1,"%s squared %s, split %s+%s\n",base17(s[i]))
<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;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if i=4 then printf(1," ...\n") end if
<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;">"%s squared %s, split %s+%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base17</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))</span>
end for</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span> <span style="color: #008080;">then</span> <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;">" ...\n"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,478 ⟶ 3,967:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def FNkaprekar
var n
dup 2 power var s
Line 3,495 ⟶ 3,984:
dup FNkaprekar IF print " " print 1 + else drop endif
endfor
nl print " Kaprekar numbers" print</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">set_time_limit(300);
 
print_r(array_filter(range(1, 10000), 'isKaprekar'));
Line 3,515 ⟶ 4,004:
}
return false;
}</langsyntaxhighlight>
 
<pre>Array
Line 3,538 ⟶ 4,027:
)
54</pre>
 
=={{header|Picat}}==
{{trans|C++}}
Using Casting out nines.
<syntaxhighlight lang="picat">go =>
println(base=10),
println(kaprekar_number(10,10000)),
nl,
println("Testing 1000000:"),
 
K10 = kaprekar_number(10,1000000),
% println(K10),
nl,
println(base=16),
K16 = [I.to_hex_string() : I in kaprekar_number(16,1000000)],
% println(K16),
nl,
println(base=17),
K17 = [to_radix_string(I,17).to_lowercase : I in kaprekar_number(17,1000000)],
% println(K17),
nl,
println(base=36),
K36 = [to_radix_string(I,36) : I in kaprekar_number(36,1000000)],
% println(K36),
 
nl.
 
kaprekar_number(Base,Limit) = Ks =>
N = ceiling(log(Base,Limit)),
PaddyCnt = 0,
Ks = [],
foreach(Nz in 1..N)
foreach(K in Base**(Nz-1)..(Base**Nz)-1, K <= Limit)
if (K*(K-1)) mod (Base-1) == 0 then
Found = false,
foreach(N2 in Nz..Nz*2-1,Found = false)
B = Base**N2,
Nr = K*(B-K) div (B-1),
Q = K-Nr,
if K*K==Q*B+Nr, 0<Nr then
PaddyCnt := PaddyCnt+1,
Ks := Ks ++ [K],
Found := true
end
end
end
end
end,
println(len=Ks.length).</syntaxhighlight>
 
{{out}}
<pre>base = 10
len = 17
[1,9,45,55,99,297,703,999,2223,2728,4879,4950,5050,5292,7272,7777,9999]
 
Testing 1000000:
len = 54
 
base = 16
len = 74
 
base = 17
len = 24
 
base = 36
len = 35</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de kaprekar (N)
(let L (cons 0 (chop (* N N)))
(for ((I . R) (cdr L) R (cdr R))
(NIL (gt0 (format R)))
(T (= N (+ @ (format (head I L)))) N) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (filter kaprekar (range 1 10000))
Line 3,553 ⟶ 4,110:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
kaprekar: procedure options (main); /* 22 January 2012 */
declare i fixed decimal (9), j fixed binary;
Line 3,575 ⟶ 4,132:
 
end kaprekar;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,598 ⟶ 4,155:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Kaprekar ([int]$Number)
{
Line 3,624 ⟶ 4,181:
return $false
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
"Kaprekar numbers less than 10,000:"
1..10000 | ForEach-Object {if (Test-Kaprekar -Number $_) {"{0,6}" -f $_}} | Format-Wide {$_} -Column 17 -Force
Line 3,631 ⟶ 4,188:
"Kaprekar numbers less than 1,000,000:"
1..1000000 | ForEach-Object {if (Test-Kaprekar -Number $_) {"{0,6}" -f $_}} | Format-Wide {$_} -Column 18 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,650 ⟶ 4,207:
=={{header|Prolog}}==
Works with SWI-Prolog, uses a list comprehension : [[List comprehensions#Prolog]]
<langsyntaxhighlight Prologlang="prolog">kaprekar_(Z, X) :-
split_number(Z, 10, X).
 
Line 3,662 ⟶ 4,219:
kaprekar(N, V) :-
V <- {X & X <- 1 .. N & ((Z is X * X, kaprekar_(Z, X)); X = 1) }.
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- kaprekar(1000, V).
Line 3,676 ⟶ 4,233:
=={{header|PureBasic}}==
{{trans|C}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Kaprekar(n.i)
nn.q = n*n
tens.q= 1
Line 3,702 ⟶ 4,259:
Print("Press ENTER to exit")
Input()
EndIf</langsyntaxhighlight>
<pre> 1: 1
2: 9
Line 3,721 ⟶ 4,278:
===Splitting strings in a loop===
(Swap the commented return statement to return the split information).
<langsyntaxhighlight lang="python">>>> def k(n):
n2 = str(n**2)
for i in range(len(n2)):
Line 3,734 ⟶ 4,291:
>>> len([x for x in range(1,1000000) if k(x)])
54
>>> </langsyntaxhighlight>
 
A stronger code that gives a list of Kaprekar numbers within a range in a given base.
The range must be given as a decimal number.
<langsyntaxhighlight lang="python">def encode(n, base):
result = ""
while n:
Line 3,766 ⟶ 4,323:
print 'The number of Kaprekar Numbers found are',
print len(KNumbers)
raw_input()</langsyntaxhighlight>
===Using Casting Out Nines Generator===
See: http://rosettacode.org/wiki/Casting_out_nines#Python for explanation and code for CastOut
<langsyntaxhighlight lang="python">
Base = 10
N = 6
Line 3,781 ⟶ 4,338:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 3,840 ⟶ 4,397:
</pre>
Other bases may be used e.g.:
<langsyntaxhighlight lang="python">
Base = 16
N = 4
Line 3,851 ⟶ 4,408:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 3,895 ⟶ 4,452:
40: e6e6
41: ffff
</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ dup 1 = if done
dup temp put
dup *
false swap 1
[ base share *
2dup /mod
over 0 = iff
2drop done
dup 0 = iff
2drop again
+ temp share = iff
[ rot not unrot ]
done
again ]
2drop
temp release ] is kaprekar ( n --> b )
say "Kaprekar numbers less than one thousand: "
[]
1000 times
[ i^ kaprekar if
[ i^ join ] ]
echo cr cr
say "Number of Kaprekar numbers less than one million: "
0
1000000 times
[ i^ kaprekar if 1+ ]
echo cr cr
say "Base 17 Kaprekar numbers less than one million." cr cr
17 base put
[]
1000000 times
[ i^ kaprekar if
[ i^ join ] ]
say "In base 17: "
dup echo cr
base release
say "In decimal: "
echo</syntaxhighlight>
 
{{out}}
 
<pre>Kaprekar numbers less than one thousand.[ 1 9 45 55 99 297 703 999 ]
 
Number of Kaprekar numbers less than one million: 54
 
Base 17 Kaprekar numbers less than one million.
In base 17: [ 1 G 3D D4 GG 556 BBB GGG 18BD 1F1F 36DB 43CD 61EB 785D 7A96 967B 98B4 AF26 CD44 DA36 F1F2 F854 GGGG 33334 ]
In decimal: [ 1 16 64 225 288 1536 3377 4912 7425 9280 16705 20736 30016 36801 37440 46081 46720 53505 62785 66816 74241 76096 83520 266224 ]
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (kaprekar? n)
Line 3,910 ⟶ 4,522:
 
(filter kaprekar? (range 1 10000))
</syntaxhighlight>
</lang>
<pre>
'(1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999)
Line 3,918 ⟶ 4,530:
(formerly Perl 6)
===String version (slow)===
<syntaxhighlight lang="raku" perl6line>sub kaprekar( Int $n ) {
my $sq = $n ** 2;
for 0 ^..^ $sq.chars -> $i {
Line 3,930 ⟶ 4,542:
print 1;
print " $_" if .&kaprekar for ^10000;
print "\n";</langsyntaxhighlight>
{{out}}
<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. <syntaxhighlight lang="raku" perl6line>sub kaprekar( Int $n, Int :$base = 10 ) {
my $hi = $n ** 2;
my $lo = 0;
Line 3,947 ⟶ 4,559:
print " $_" if .&kaprekar for ^10_000;
 
my atomicint $n;
(^1_000_000).race.map: { $n++ if kaprekar $_ }
say "\n\nBase 10 Kaprekar numbers < :10<1_000_000> = $n";
Line 3,965 ⟶ 4,577:
}
 
.say for @results.sort({$^a.chars <=>: $^b*.chars});</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
Line 4,032 ⟶ 4,644:
 
===Casting out nines (fast)===
<syntaxhighlight lang="raku" perl6line>sub kaprekar-generator( :$base = 10 ) {
my $base-m1 = $base - 1;
gather loop (my $place = 1; ; ++$place) {
Line 4,072 ⟶ 4,684:
$l17 = '0' x ($s17.chars - $h17.chars - $l17.chars) ~ $l17;
say "$n $n17 $s17 ($h17 + $l17)";
}</langsyntaxhighlight>
(Same output.)
 
=={{header|REXX}}==
╔═══════════════════════════════════════════════════════════════════╗
<lang rexx>/*REXX pgm generates & counts (+ maybe shows) some Kaprekar #s using the cast─out─9 test*/
║ Kaprekar numbers were thought of by the mathematician from India, ║
/*╔═══════════════════════════════════════════════════════════════════╗
Shri Dattathreya Ramachardra Kaprekar (1905 ───► Kaprekar1986). numbers were thought of by the mathematician from India,
╚═══════════════════════════════════════════════════════════════════╝
║ Shri Dattathreya Ramachardra Kaprekar (1905 ───► 1986). ║
<syntaxhighlight lang="rexx">/*REXX pgm generates & counts (& maybe shows) some Kaprekar #s using the cast─out─9 test*/
╚═══════════════════════════════════════════════════════════════════╝*/
parse arg A B . /*obtain optional arguments from the CL*/
if A=='' | A="," then A= 10000 /*Not specified? Then use the default.*/
if B=='' | B="," then B= -1000000 /* " " " " " " */
call Kaprekar A /*gen Kaprekar numbers, and showdisplay 'em.*/
call Kaprekar B /* " " " don't show 'em " " */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Kaprekar: procedure; parse arg N; #=0; aN= abs(N) /*setobtain counterthe to zerolimit; use │N│ value. */
numeric digits max(9, 2 * length(NaN) ) /*use enough decimal digits for square.*/
ifd= aN>0digits(); then call tell 1 tell= N>0 /*unityset is definedD to benumber aof Kaprekardigits; #. set TELL.*/
#= 0; if aN>0 then do; #= 1; if tell then say right(1, d); end
/* [↑] handle case of N being unity.*/
if aN>1 then do j=9 for aN-9 ; /*calculate the square of J (S). */
ifjc= j//9 >2 then iterate /*IsJC: J modmodulo 9 > two? (cast Thenout skip this Jnines). */
if jc >2 then iterate /*Is J mod 9 > two? Then skip this J.*/
s= j*j /*calculate the square of J (S). */
if j//9jc==s//9 then do k=1 for length(s)%2 /*≡ casted out 9's? */
parse var s L +(k) R
if j\==L+R then do; call tell j; leave; enditerate
#= # end+ 1; /*k*/ if tell then say right(j, d); leave
end /*k*/
end /*j*/
say
say center(" There're " # ' Kaprekar numbers below ' aN" || .", 79, "═")
return</syntaxhighlight>
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: #=#+1; if N>0 then say right(arg(1), digits()); return /*maybe display it*/</lang>
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> &nbsp; 10000 &nbsp; -1000000 </tt>}}
<pre>
1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999
 
═════════════════ There're 17 Kaprekar numbers below 10000. ═════════════════
 
════════════════ There're 54 Kaprekar numbers below 1000000. ════════════════
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nr = 0
for i = 1 to 200
Line 4,150 ⟶ 4,763:
end
return (n = 1)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,159 ⟶ 4,772:
5 : 99
total kaprekar numbers under 200 = 5
</pre>
 
=={{header|RPL}}==
{{trans|Python}}
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ DUP SQ →STR DUP SIZE → n n2 n2s
≪ 1 CF 1 n2s 1 - '''FOR''' j
'''IF''' n2 j 1 + n2s SUB STR→ '''THEN'''
LAST n2 1 j SUB STR→
'''IF''' DUP2 + n ==
'''THEN''' 1 SF n2s 'j' STO '''ELSE''' DROP2 '''END'''
'''END'''
'''NEXT'''
'''IF''' 1 FS?
'''THEN''' n →STR "=" + SWAP →STR + "+" + SWAP →STR +
'''ELSE''' "" '''END'''
≫ ≫ ''''KPREK'''' STO
≪ { 1 } 9 10000 '''FOR''' n 0 1 '''FOR''' k
n k + '''KPREK''' IF DUP "" ≠ '''THEN''' + '''ELSE''' DROP '''END'''
'''NEXT''' 9 '''STEP'''
≫ ''''TASK'''' STO
|
'''KPREK''' ''( n -- string )''
Examine all the possible a|b cuts of n²
if b is not zero
restore b in stack and get a
if a + b == n
then exit loop
if a and b found
then edit result
else return an empty string
'''TASK''': Loop ad examine
only numbers mod 9 = 0 or 1 (see Maple section)
|}
{{out}}
<pre>
1: { 1 "9=8+1" "45=20+25" "55=30+25" "99=98+1" "297=88+209" "703=494+209" "999=998+1" "2223=494+1729" "2728=744+1984" "4879=238+4641" "4950=2450+2500" "5050=2550+2500" "5292=28+5264" "7272=5288+1984" "7777=6048+1729" "9999=9998+1" }
</pre>
 
=={{header|Ruby}}==
with extra extra credit
<langsyntaxhighlight lang="ruby">def kaprekar(n, base = 10)
return [1, 1, 1, ""] if n == 1
return if n*(n-1) % (base-1) != 0 # casting out nine
Line 4,194 ⟶ 4,856:
puts "%7s %5s %9s %s + %s" % [decimal, *result]
end
end</langsyntaxhighlight>
 
{{out}}
Line 4,245 ⟶ 4,907:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 5000
x$ = str$(i * i)
if i = 1 then x$ = "10"
Line 4,251 ⟶ 4,913:
if (val(left$(x$,j)) + val(mid$(x$,j+1)) = i and val(mid$(x$,j+1)) <> 0) or i = 1 then print "Kaprekar :";left$(x$,j);" + ";mid$(x$,j+1);" = ";i
next j
next i</langsyntaxhighlight><pre>Kaprekar :1 + 0 = 1
Kaprekar :8 + 1 = 9
Kaprekar :20 + 25 = 45
Line 4,265 ⟶ 4,927:
=={{header|Scala}}==
{{works with|Scala|2.9.1}}
<langsyntaxhighlight Scalalang="scala">object Kaprekar extends App {
 
def isKaprekar(n: Int, base: Int = 10):Option[Triple[String,String,String]] = {
Line 4,303 ⟶ 4,965:
println(k3.size + " Kaprekar numbers < 1000000 (b:10) for base 17"+"\n"*2)
 
}</langsyntaxhighlight>
{{out}}
<pre style="height: 40ex; overflow: scroll">1
Line 4,409 ⟶ 5,071:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; auxiliary functions : range, filter
(define (range a b)
(let loop ((v '()) (i b))
Line 4,435 ⟶ 5,097:
 
(filter kaprekar? (range 1 10000))
; (1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999)</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 4,499 ⟶ 5,161:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,588 ⟶ 5,250:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var kapr = Set()
 
for n in (1..15) {
Line 4,603 ⟶ 5,265:
var k = (10**n - 1)
printf("Kaprekar numbers <= 10^%2d: %5d\n", n, kapr.count_by { .<= k })
}</langsyntaxhighlight>
 
{{out}}
Line 4,620 ⟶ 5,282:
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">kap,n = getkap(1000000)
> i, 1..n
<< kap[i]!<10000
Line 4,639 ⟶ 5,301:
<
<= kap,#.size(kap,1)
.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,663 ⟶ 5,325:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5; # Arbitrary precision arithmetic, for stretch goal only
proc kaprekar n {
if {$n == 1} {return 1}
Line 4,687 ⟶ 5,349:
incr kcount [kaprekar $i]
}
puts "$kcount Kaprekar numbers less than 1000000"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,696 ⟶ 5,358:
=={{header|Ursala}}==
First we define a function <code>kd</code> parameterized by a pair of functions <code>p</code> and <code>r</code> for printing and reading natural numbers, which takes a natural number to its Kaprekar decomposition if any.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 4,703 ⟶ 5,365:
#cast %nLnX
 
t = ^|(~&,length) (iota; :/1+ ~&rFlS+ * ^/~& kd\%np ~&h+ %nP)~~/10000 1000000</langsyntaxhighlight>
The <code>kd</code> function parameterized by the built in decimal printing and reading functions is applied to the sequences from zero to 10000 and zero to 1000000, with the results filtered according to whether the decomposition exists. The inputs in the former case and the length in the latter are shown.
<pre>
Line 4,728 ⟶ 5,390:
</pre>
For the rest of the task, functions <code>p</code> and <code>r</code> are defined for numbers in base 17.
<langsyntaxhighlight Ursalalang="ursala">p = ||'0'! ~&a^& ^|J(~&,division\17); ^lrNCT/~&falPR @ar -$/iota17 digits--'abcdefg'
 
r = sum^|(~&,product/17)=>0+ *x -$/digits--'abcdefg' iota17
Line 4,734 ⟶ 5,396:
#show+
 
t = mat` *K7 pad` *K7 ^C(~&h+ %nP@l,p*+ <.~&l,product@llX,~&rl,~&rr>)*rF ^(~&,kd/p r@h)* iota 1000000</langsyntaxhighlight>
The <code>kd</code> function is parameterized by them and a table of results for numbers between 1 and 1000000 is displayed.
<pre>
Line 4,764 ⟶ 5,426:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
ReadOnly max As ULong = 1000000
Line 4,814 ⟶ 5,476:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 4,836 ⟶ 5,498:
 
54 numbers below 1000000 are kaprekar numbers</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="go">import strconv
 
fn kaprekar(n u64, base u64) (bool, int) {
mut order := 0
if n == 1 {
return true, -1
}
nn, mut power := n*n, u64(1)
for power <= nn {
power *= base
order++
}
power /= base
order--
for ; power > 1; power /= base {
q, r := nn/power, nn%power
if q >= n {
return false, -1
}
if q+r == n {
return true, order
}
order--
}
return false, -1
}
fn main() {
mut max := u64(10000)
println("Kaprekar numbers < $max:")
for m := u64(0); m < max; m++ {
isk, _ := kaprekar(m, 10)
if isk {
println(" $m")
}
}
// extra credit
max = u64(1e6)
mut count := 0
for m := u64(0); m < max; m++ {
isk, _ := kaprekar(m, 10)
if isk {
count++
}
}
println("\nThere are $count Kaprekar numbers < ${max}.")
// extra extra credit
base := 17
max_b := "1000000"
println("\nKaprekar numbers between 1 and ${max_b}(base ${base}):")
max, _ = strconv.common_parse_uint2(max_b, base, 64)
println("\n Base 10 Base ${base} Square Split")
for m := u64(2); m < max; m++ {
isk, pos := kaprekar(m, u64(base))
if !isk {
continue
}
sq := strconv.format_uint(m*m, base)
str := strconv.format_uint(m, base)
split := sq.len-pos
println("${m:8} ${str:7} ${sq:12} ${sq[..split]:6} + ${sq[split..]}") // optional extra extra credit
}
}</syntaxhighlight>
{{out}}
<pre>Same as Go output</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
isKap &n [
@var s +'' *n n
Line 4,856 ⟶ 5,593:
!console.log "Number of Kaprekar numbers below 1000000: {#!-isKap @to 1M}"
]
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000: 1,9,45,55,99,297,703,999,2223,2728,4879,4950,5050,5292,7272,7777,9999
Line 4,864 ⟶ 5,601:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt, Conv
 
var kaprekar = Fn.new { |n, base|
Line 4,916 ⟶ 5,653:
Fmt.print("$8d $7s $12s $6s + $s", m, str, sq, sq[0...split], sq[split..-1])
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,007 ⟶ 5,744:
numbers up to 1,000,000. Floating point (double) provides 15 decimal digits of precision.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func Kaprekar(N, B); \Returns 'true' if N is a Kaprekar number in base B
Line 5,039 ⟶ 5,776:
[Text(0, " "); IntOut(0, N)];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 5,050 ⟶ 5,787:
=={{header|Yabasic}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">clear screen
n = 0
FOR i = 1 TO 999999
Line 5,072 ⟶ 5,809:
loop
return (n=1)
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn isKaprekarB(n,b=10){
powr:=n*n;
r:=l:=0; tens:=b;
Line 5,086 ⟶ 5,823:
}
return(False);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("Kaprekar number <= 10,000:\n",
[1..].filter(T(isKaprekarB, fcn(n){ if(n>=10000) Void.Stop else True })));
 
Line 5,096 ⟶ 5,833:
kbs:=[1..].filter(T(isKaprekarB.fp1(17),
fcn(n){ if(n>=0d1_000_000) Void.Stop else True }));
Utils.zipWith(fcn(k,n){ "%3d: %7d == %.17B".fmt(n,k,k).println() },kbs,[1..]);</langsyntaxhighlight>
{{out}}
<pre>
2,021

edits