Kaprekar numbers: Difference between revisions

Added Easylang
m (→‎Numeric version (medium): simpler sort expression)
(Added Easylang)
 
(14 intermediate revisions by 12 users not shown)
Line 51:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F k(n)
V n2 = String(Int64(n) ^ 2)
L(i) 0 .< n2.len
Line 61:
 
print((1..9999).filter(x -> k(x)))
print((1..999999).filter(x -> k(x)).len)</langsyntaxhighlight>
 
{{out}}
Line 71:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Kaprekar numbers 22/03/ 2017
KAPREKAR CSECT
USING KAPREKAR,R13 base register
Line 165:
PG DC CL80' ' buffer
YREGS
END KAPREKAR</langsyntaxhighlight>
{{out}}
<pre>
Line 196:
so i chose base 17 (17 ** 6).
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Strings.Fixed;
 
Line 326:
end loop;
Ada.Text_IO.Put_Line (" Total:" & Integer'Image (Count));
end Kaprekar2;</langsyntaxhighlight>
 
{{out}}
Line 335:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># find some Kaprekar numbers #
 
# returns TRUE if n is a Kaprekar number, FALSE otherwise #
Line 378:
print( ( newline ) );
print( ( "There are ", whole( k count, 0 ), " Kaprekar numbers below ", whole( max number, 0 ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 388:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">k?: function [n][
n2: to :string n*n
loop 0..dec size n2 'i [
Line 400:
loop 1..10000 'x [
if k? x -> print x
]</langsyntaxhighlight>
 
{{out}}
Line 424:
=={{header|AutoHotkey}}==
Function:
<langsyntaxhighlight AutoHotkeylang="autohotkey">Kaprekar(L) {
Loop, % L + ( C := 0 ) {
S := ( N := A_Index ) ** 2
Line 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 446:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KAPREKAR_NUMBERS.AWK
BEGIN {
Line 472:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 496:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 555:
set /a tempcount+=1
goto lengthloop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 577:
</pre>
 
=={{header|BASIC}}==
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">n = 0
for i = 1 to 1999999
if Kaprekar(i) then
Line 599:
until t <= n
return n = 1
end function</langsyntaxhighlight>
 
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
n% = 0
FOR i% = 1 TO 999999
Line 624 ⟶ 623:
IF s-n = INT(s/t)*(t-1) THEN = TRUE
UNTIL FALSE
= (n=1)</langsyntaxhighlight>
{{out}}
<pre>
Line 655 ⟶ 654:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( 0:?n
& 1:?count
& out$(!count 1)
Line 672 ⟶ 671:
)
& out$(str$("There are " !count " kaprekar numbers less than 1000000"))
);</langsyntaxhighlight>
{{out}}
<pre>1 1
Line 694 ⟶ 693:
 
=={{header|Brat}}==
<langsyntaxhighlight Bratlang="brat">kaprekar = { limit |
results = []
 
Line 720 ⟶ 719:
 
p "Number of Kaprekar numbers below 1,000,000:"
p kaprekar(1000000).length</langsyntaxhighlight>
 
{{out}}
Line 732 ⟶ 731:
=={{header|C}}==
Sample for extra extra credit:
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
Line 790 ⟶ 789:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>base 10:
Line 839 ⟶ 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 942 ⟶ 941:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,007 ⟶ 1,006:
}
 
}</langsyntaxhighlight>
 
{{out}}
Line 1,068 ⟶ 1,067:
=={{header|C++}}==
===Using String Manipulation (very slow)===
<langsyntaxhighlight lang="cpp">#include <vector>
#include <string>
#include <iostream>
Line 1,121 ⟶ 1,120:
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers up to 10000:
Line 1,155 ⟶ 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,178 ⟶ 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,235 ⟶ 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,284 ⟶ 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,302 ⟶ 1,301:
}}
return 0;
}</langsyntaxhighlight>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,359 ⟶ 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,407 ⟶ 1,406:
 
=={{header|CLU}}==
<langsyntaxhighlight 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
Line 1,492 ⟶ 1,491:
display(po, i, 17)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10,000:
Line 1,541 ⟶ 1,540:
=={{header|CoffeeScript}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="coffeescript">splitAt = (str, idx) ->
ans = [ str.substring(0, idx), str.substring(idx) ]
if ans[0] == ""
Line 1,569 ⟶ 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,585 ⟶ 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,626 ⟶ 1,625:
(terpri)
(ktest 1000000 17)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,650 ⟶ 1,649:
</pre>
===In the style of the C++ generator===
<langsyntaxhighlight lang="lisp">
;; Generate Kaprekar Numbers using Casting Out Nines Generator
;;
Line 1,665 ⟶ 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,812 ⟶ 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,835 ⟶ 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,842 ⟶ 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,862 ⟶ 1,861:
if (i.isKaprekar)
writefln("%d: %d", count++, i);
}</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 1,886 ⟶ 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,940 ⟶ 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,987 ⟶ 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 2,038 ⟶ 2,134:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-mode(compile).
-import(lists, [seq/2]).
Line 2,066 ⟶ 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 2,077 ⟶ 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 2,094 ⟶ 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 2,134 ⟶ 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 2,152 ⟶ 2,248:
 
1,000,000 [1,b] [ kaprekar? ] filter dup . length
"Count of Kaprekar numbers <= 1,000,000: " write .</langsyntaxhighlight>
{{out}}
<pre>
Line 2,185 ⟶ 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 2,203 ⟶ 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,244 ⟶ 2,340:
if (printnums .eqv. .false.) write(*, "(i0)") c
end subroutine
end program</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,267 ⟶ 2,363:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-12-2016
' compile with: fbc -s console
 
Line 2,331 ⟶ 2,427:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 2,353 ⟶ 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,465 ⟶ 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,542 ⟶ 2,816:
str, sq, sq[:split], sq[split:]) // optional extra extra credit
}
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10000:
Line 2,627 ⟶ 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,657 ⟶ 2,931:
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base " + base)
}
}</langsyntaxhighlight>
{{out}}
<pre>1 1 1 0 + 1
Line 2,716 ⟶ 2,990:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Text.Printf (printf)
import Data.Maybe (mapMaybe)
import Numeric (showIntAtBase)
Line 2,757 ⟶ 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,811 ⟶ 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,860 ⟶ 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,874 ⟶ 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,898 ⟶ 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,960 ⟶ 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 3,014 ⟶ 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 3,060 ⟶ 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 3,071 ⟶ 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 3,083 ⟶ 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 3,096 ⟶ 3,370:
kaprekar( 1, 255, 16)
kaprekar( 1, 255, 16, 16)
kaprekar( 1, 288, 17, 17)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,118 ⟶ 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 3,149 ⟶ 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 3,166 ⟶ 3,440:
 
@show filter(iskaprekar, 1:10000)
@show count(iskaprekar, 1:10000)</langsyntaxhighlight>
 
{{out}}
Line 3,174 ⟶ 3,448:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.lang.Long.parseLong
import java.lang.Long.toString
 
Line 3,208 ⟶ 3,482:
}
println("$count Kaprekar numbers < $max (base 10) in base $base")
}</langsyntaxhighlight>
{{out}}
<pre> 1 1 1 0 + 1
Line 3,267 ⟶ 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,286 ⟶ 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,321 ⟶ 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,329 ⟶ 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,355 ⟶ 3,629:
 
showKaprekar(10000);
countKaprekar(1000000);</langsyntaxhighlight>
 
{{out}}
Line 3,362 ⟶ 3,636:
 
=={{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],
Line 3,368 ⟶ 3,642:
i++]; last];
Select[Range[10000], KaprekaQ]
Length[Select[Range[1000000], KaprekaQ]]</langsyntaxhighlight>
{{out}}
<pre>{1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999}
Line 3,374 ⟶ 3,648:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">kaprekarp(n) := block(
[p, q, a, b],
if n = 1 then true else (
Line 3,398 ⟶ 3,672:
 
length(%);
54</langsyntaxhighlight>
 
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">local
val base = 10;
fun kaprekar
Line 3,436 ⟶ 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,446 ⟶ 3,720:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Kaprekar;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
Line 3,508 ⟶ 3,782:
 
ReadChar
END Kaprekar.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils, sequtils
proc k(n: int): bool =
Line 3,522 ⟶ 3,796:
echo toSeq(1..10_000).filter(k)
echo len toSeq(1..1_000_000).filter(k)</langsyntaxhighlight>
 
{{out}}
Line 3,529 ⟶ 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,550 ⟶ 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,560 ⟶ 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,576 ⟶ 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,587 ⟶ 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,603 ⟶ 3,877:
printf "Kaprekar numbers <= 10^%2d: %5d\n",
$n, scalar(grep { $_ <= $np } @kap);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,618 ⟶ 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,690 ⟶ 3,967:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def FNkaprekar
var n
dup 2 power var s
Line 3,707 ⟶ 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,727 ⟶ 4,004:
}
return false;
}</langsyntaxhighlight>
 
<pre>Array
Line 3,750 ⟶ 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,765 ⟶ 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,787 ⟶ 4,132:
 
end kaprekar;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,810 ⟶ 4,155:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Kaprekar ([int]$Number)
{
Line 3,836 ⟶ 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,843 ⟶ 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,862 ⟶ 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,874 ⟶ 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,888 ⟶ 4,233:
=={{header|PureBasic}}==
{{trans|C}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Kaprekar(n.i)
nn.q = n*n
tens.q= 1
Line 3,914 ⟶ 4,259:
Print("Press ENTER to exit")
Input()
EndIf</langsyntaxhighlight>
<pre> 1: 1
2: 9
Line 3,933 ⟶ 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,946 ⟶ 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,978 ⟶ 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,993 ⟶ 4,338:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 4,052 ⟶ 4,397:
</pre>
Other bases may be used e.g.:
<langsyntaxhighlight lang="python">
Base = 16
N = 4
Line 4,063 ⟶ 4,408:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 4,111 ⟶ 4,456:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ dup 1 = if done
<lang Quackery>
[ dup dup *temp put
dup *
9 mod swap 9 mod != ] is castout9 ( n --> b )
false swap 1
 
[ [] base share *
[ swap 102dup /mod
rotover join0 = iff
over 0 = until ]2drop done
dup 0 = iff
nip ] is ->digits ( n --> [ )
2drop again
+ temp share = iff
[ 0 swap witheach
[ rot not unrot ]
[ swap 10 * + ] ] is ->number ( [ --> n )
done
 
again ]
[ dup castout9 iff
2drop
[ drop false ] done
temp release ] is kaprekar ( n --> b )
dup 1 = if done
false swap
say "Kaprekar numbers less than one thousand: "
dup temp put
[]
dup * ->digits
dup size 1 -1000 times
[ dup i^ 1+ split
->number
dup 0 = iff
[ conclude 2drop ]
done
swap ->number +
temp share = if
[ dip not conclude ] ]
drop temp release ] is kaprekar ( n --> b )
 
say "Kaprekar numbers below 10000" cr
[] 10000 times
[ i^ kaprekar if
[ i^ join ] ]
echo cr cr
cr cr
say "Number of Kaprekar numbers belowless 1000000than one million: "
0
0 1000000 times
1000000 times
[ i^ kaprekar if 1+ ]
echo</lang> 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 belowless 10000than one thousand.[ 1 9 45 55 99 297 703 999 ]
[ 1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999 ]
 
Number of Kaprekar numbers belowless 1000000than one million: 54</pre>
 
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 4,172 ⟶ 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 4,180 ⟶ 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 4,192 ⟶ 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 4,227 ⟶ 4,577:
}
 
.say for @results.sort: *.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,294 ⟶ 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,334 ⟶ 4,684:
$l17 = '0' x ($s17.chars - $h17.chars - $l17.chars) ~ $l17;
say "$n $n17 $s17 ($h17 + $l17)";
}</langsyntaxhighlight>
(Same output.)
 
Line 4,342 ⟶ 4,692:
║ Shri Dattathreya Ramachardra Kaprekar (1905 ───► 1986). ║
╚═══════════════════════════════════════════════════════════════════╝
<langsyntaxhighlight 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.*/
Line 4,367 ⟶ 4,717:
say
say center(" There're " # ' Kaprekar numbers below ' aN" ", 79, "═")
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> &nbsp; 10000 &nbsp; -1000000 </tt>}}
<pre>
Line 4,394 ⟶ 4,744:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nr = 0
for i = 1 to 200
Line 4,413 ⟶ 4,763:
end
return (n = 1)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,422 ⟶ 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,457 ⟶ 4,856:
puts "%7s %5s %9s %s + %s" % [decimal, *result]
end
end</langsyntaxhighlight>
 
{{out}}
Line 4,508 ⟶ 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,514 ⟶ 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,528 ⟶ 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,566 ⟶ 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,672 ⟶ 5,071:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; auxiliary functions : range, filter
(define (range a b)
(let loop ((v '()) (i b))
Line 4,698 ⟶ 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,762 ⟶ 5,161:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,851 ⟶ 5,250:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var kapr = Set()
 
for n in (1..15) {
Line 4,866 ⟶ 5,265:
var k = (10**n - 1)
printf("Kaprekar numbers <= 10^%2d: %5d\n", n, kapr.count_by { .<= k })
}</langsyntaxhighlight>
 
{{out}}
Line 4,883 ⟶ 5,282:
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">kap,n = getkap(1000000)
> i, 1..n
<< kap[i]!<10000
Line 4,902 ⟶ 5,301:
<
<= kap,#.size(kap,1)
.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,926 ⟶ 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,950 ⟶ 5,349:
incr kcount [kaprekar $i]
}
puts "$kcount Kaprekar numbers less than 1000000"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,959 ⟶ 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,966 ⟶ 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,991 ⟶ 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,997 ⟶ 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 5,027 ⟶ 5,426:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
ReadOnly max As ULong = 1000000
Line 5,077 ⟶ 5,476:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 5,099 ⟶ 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 5,119 ⟶ 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 5,127 ⟶ 5,601:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt, Conv
 
var kaprekar = Fn.new { |n, base|
Line 5,179 ⟶ 5,653:
Fmt.print("$8d $7s $12s $6s + $s", m, str, sq, sq[0...split], sq[split..-1])
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,270 ⟶ 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,302 ⟶ 5,776:
[Text(0, " "); IntOut(0, N)];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 5,313 ⟶ 5,787:
=={{header|Yabasic}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">clear screen
n = 0
FOR i = 1 TO 999999
Line 5,335 ⟶ 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,349 ⟶ 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,359 ⟶ 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,018

edits