Kaprekar numbers: Difference between revisions

Added Easylang
(Added Easylang)
 
(37 intermediate revisions by 28 users not shown)
Line 2:
 
A positive integer is a [[wp:Kaprekar number|Kaprekar number]] if:
* It is   '''1'''     (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
<br>Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
 
 
;Example Kaprekar numbers:
* <math>2223</math> is a Kaprekar number, as <math>2223 * 2223 = 4941729</math>, <math>4941729</math> may be split to <math>494</math> and <math>1729</math>, and <math>494 + 1729 = 2223</math>.
* The series of Kaprekar numbers is known as [[oeis:A006886|A006886]], and begins as <math>1, 9, 45, 55, ...</math>.
 
 
;Example process:
Line 16 ⟶ 18:
* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.
 
 
;Task description:
;Task:
Generate and show all Kaprekar numbers less than 10,000.
 
 
;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
 
 
;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.
 
 
For this purpose, do the following:
Line 32 ⟶ 38:
<br>For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:<pre>225 d4 a52g a5 + 2g</pre>
 
 
;Reference:
* [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html The Kaprekar Numbers] by Douglas E. Iannucci (2000). [http://pictor.math.uqam.ca/~plouffe/OEIS/jis/The%20Kaprekar%20Numbers.pdf PDF version]
 
;related task
 
[[Casting out nines]]
;Related task:
<br>
* &nbsp; [[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 135 ⟶ 165:
PG DC CL80' ' buffer
YREGS
END KAPREKAR</langsyntaxhighlight>
{{out}}
<pre>
Line 159 ⟶ 189:
54 999999
</pre>
 
 
=={{header|Ada}}==
Line 167 ⟶ 196:
so i chose base 17 (17 ** 6).
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Strings.Fixed;
 
Line 297 ⟶ 326:
end loop;
Ada.Text_IO.Put_Line (" Total:" & Integer'Image (Count));
end Kaprekar2;</langsyntaxhighlight>
 
{{out}}
Line 306 ⟶ 335:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># find some Kaprekar numbers #
 
# returns TRUE if n is a Kaprekar number, FALSE otherwise #
Line 349 ⟶ 378:
print( ( newline ) );
print( ( "There are ", whole( k count, 0 ), " Kaprekar numbers below ", whole( max number, 0 ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 356 ⟶ 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 373 ⟶ 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 381 ⟶ 446:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KAPREKAR_NUMBERS.AWK
BEGIN {
Line 407 ⟶ 472:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 429 ⟶ 494:
54 Kaprekar numbers < 1000000
</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 489 ⟶ 555:
set /a tempcount+=1
goto lengthloop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 511 ⟶ 577:
</pre>
 
=={{header|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 534 ⟶ 623:
IF s-n = INT(s/t)*(t-1) THEN = TRUE
UNTIL FALSE
= (n=1)</langsyntaxhighlight>
{{out}}
<pre>
Line 565 ⟶ 654:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( 0:?n
& 1:?count
& out$(!count 1)
Line 582 ⟶ 671:
)
& out$(str$("There are " !count " kaprekar numbers less than 1000000"))
);</langsyntaxhighlight>
{{out}}
<pre>1 1
Line 604 ⟶ 693:
 
=={{header|Brat}}==
<langsyntaxhighlight Bratlang="brat">kaprekar = { limit |
results = []
 
Line 630 ⟶ 719:
 
p "Number of Kaprekar numbers below 1,000,000:"
p kaprekar(1000000).length</langsyntaxhighlight>
 
{{out}}
Line 642 ⟶ 731:
=={{header|C}}==
Sample for extra extra credit:
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
Line 700 ⟶ 789:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>base 10:
Line 749 ⟶ 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 852 ⟶ 941:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
public class KaprekarNumbers {
 
/// <summary>
/// The entry point of the program, where the program control starts and ends.
/// </summary>
public static void Main() {
int count = 0;
 
foreach ( ulong i in _kaprekarGenerator(999999) ) {
Console.WriteLine(i);
count++;
}
 
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
}
 
/// <summary>
/// Generator function which generates the Kaprekar numbers.
/// </summary>
/// <returns>The generator.</returns>
/// <param name="max">The maximum value of the numbers generated.</param>
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
 
ulong next = 1;
 
// 1 is always a Kaprekar number.
yield return next;
 
for ( next = 2; next <= max; next++ ) {
 
ulong square = next * next;
 
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
// Check the square against each power of 10 from 10^1 to 10^19 (highest which can be
// represented by a ulong)
 
// If the power of 10 to be checked against is greater than or equal to the square, stop checking
if ( square <= check )
break;
 
// Given a power of 10 as 10^n, the remainder when dividing the square number by that power
// of 10 is equal to the last n digits of the number (starting from the right) and the
// quotient gives the remaining digits.
// If the last n digits are all zeroes, then the remainder will be zero, which is not
// accepted.
 
ulong r = square % check;
ulong q = (square - r) / check;
 
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
 
}
 
}
 
}</syntaxhighlight>
 
{{out}}
<pre>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
There are 54 Kaprekar numbers less than 1000000.</pre>
 
=={{header|C++}}==
===Using String Manipulation (very slow)===
<langsyntaxhighlight lang="cpp">#include <vector>
#include <string>
#include <iostream>
Line 909 ⟶ 1,120:
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers up to 10000:
Line 943 ⟶ 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 966 ⟶ 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,023 ⟶ 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,072 ⟶ 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,086 ⟶ 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,147 ⟶ 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,194 ⟶ 1,405:
41: ffff is fffe + 1 and squared is fffe0001. It is a member of Residual Set 0</pre>
 
=={{header|C sharpCLU}}==
<syntaxhighlight lang="clu">% This program assumes a 64-bit system.
<lang csharp>using System;
% On a 32-bit system, the main task (show Kaprekar numbers < 10,000)
using System.Collections.Generic;
% will run correctly, but the extra credit part will crash with
% an overflow exception.
 
% Yield all positive splits of a number
public class KaprekarNumbers {
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,
/// <summary>
% return the proper split.
/// The entry point of the program, where the program control starts and ends.
kap_split = struct[left, right: int]
/// </summary>
maybe_kap = oneof[yes: kap_split, no: null]
public static void Main() {
kaprekar = proc (n, base: int) returns (maybe_kap)
int count = 0;
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
foreach ( ulong i in _kaprekarGenerator(999999) ) {
to_base = proc (n, base: int) returns (string)
Console.WriteLine(i);
own digits: string := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
count++;
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
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
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 ()
/// <summary>
po: stream := stream$primary_output()
/// Generator function which generates the Kaprekar numbers.
/// </summary>
% Find and output all the Kaprekar numbers under 10,000.
/// <returns>The generator.</returns>
stream$putl(po, "Kaprekar numbers < 10,000:")
/// <param name="max">The maximum value of the numbers generated.</param>
for i: int in int$from_to(1, 9999) do
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
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.
ulong next = 1;
 
Base-17 Kaprekar numbers < 1,000,000:
// 1 is always a Kaprekar number.
16 yield return next;G F1 F + 1
64 3D E2G E + 2G
 
225 forD4 ( next = 2; next <= max; next++ )A52G A5 + {2G
288 GG GF01 GF + 1
 
1536 556 ulong square1B43B2 = next1B4 *+ next;3B2
3377 BBB 8093B2 809 + 3B2
 
4912 GGG GGF001 GGF + 1
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
7425 18BD 24E166G 24E + 166G
// Check the square against each power of 10 from 10^1 to 10^19 (highest which can be
9280 1F1F 39B1B94 39B + // represented by a ulong)1B94
16705 36DB B992C42 B99 + 2C42
 
20736 43CD 10DE32FG 10DE + 32FG
// If the power of 10 to be checked against is greater than or equal to the square, stop checking
30016 61EB 23593F92 2359 + 3F92
if ( square <= check )
36801 785D 351E433G 351E + break;433G
37440 7A96 37144382 3714 + 4382
 
46081 967B 52G94382 52G9 + 4382
// Given a power of 10 as 10^n, the remainder when dividing the square number by that power
46720 98B4 5575433G 5575 + 433G
// of 10 is equal to the last n digits of the number (starting from the right) and the
53505 AF26 6GA43F92 6GA4 + 3F92
// quotient gives the remaining digits.
62785 CD44 9A5532FG 9A55 + 32FG
// If the last n digits are all zeroes, then the remainder will be zero, which is not
66816 DA36 AEG42C42 AEG4 + // accepted.2C42
74241 F1F2 D75F1B94 D75F + 1B94
 
76096 F854 E1F5166G E1F5 + 166G
ulong r = square % check;
83520 GGGG GGGF0001 GGGF + 1
ulong q = (square - r) / check;
266224 33334 A2C52A07G A2C5 + 2A07G</pre>
 
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
 
}
 
}
 
}</lang>
 
{{out}}
<pre>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
There are 54 Kaprekar numbers less than 1000000.</pre>
 
=={{header|CoffeeScript}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="coffeescript">splitAt = (str, idx) ->
ans = [ str.substring(0, idx), str.substring(idx) ]
if ans[0] == ""
Line 1,346 ⟶ 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,362 ⟶ 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,403 ⟶ 1,625:
(terpri)
(ktest 1000000 17)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,427 ⟶ 1,649:
</pre>
===In the style of the C++ generator===
<langsyntaxhighlight lang="lisp">
;; Generate Kaprekar Numbers using Casting Out Nines Generator
;;
Line 1,442 ⟶ 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,589 ⟶ 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,612 ⟶ 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,619 ⟶ 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,639 ⟶ 1,861:
if (i.isKaprekar)
writefln("%d: %d", count++, i);
}</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 1,663 ⟶ 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,716 ⟶ 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,762 ⟶ 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,813 ⟶ 2,134:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-mode(compile).
-import(lists, [seq/2]).
Line 1,841 ⟶ 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,852 ⟶ 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,869 ⟶ 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,909 ⟶ 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].
<lang factor>
<syntaxhighlight lang="factor">USING: grouping.extrasio kernel mathlists mathlists.parserlazy locals math math.rangesfunctions
math.text.utilsranges prettyprint sequences sequences.extras;
splitting ;
IN: rosetta-code.kaprekar
 
:: digitskaprekar? ( n -- digits? )
1n digit-groupssq reverse:> ;sqr
1 lfrom
[ 10 swap ^ ] lmap-lazy
[ n > ] lfilter
[ sqr swap mod n < ] lwhile
list>array
[ 1 - sqr n - swap mod zero? ] any?
n 1 = or ;
 
1,000,000 [1,b] [ kaprekar? ] filter dup . length
: digit-pairs ( digits -- seq1 seq2 )
"Count of Kaprekar numbers <= 1,000,000: " write .</syntaxhighlight>
[ tail-clump ] [ head-clump ] bi [ 1 rotate ] dip ;
 
: digit-pairs>number-pairs ( seq1 seq2 -- seq1' seq2' )
[ [ 10 digits>integer ] map but-last ] bi@ ;
 
: remove-zeros ( seq1 seq2 -- seq1' seq2' )
[ [ 0 = ] split1-when drop ] bi@ ;
 
: kaprekar-pairs ( n -- seq1 seq2 )
digits digit-pairs digit-pairs>number-pairs remove-zeros ;
 
: kaprekar? ( n -- ? )
dup sq kaprekar-pairs [ + ] 2map member? ;
 
: main ( -- )
10000 [1,b) [ kaprekar? ] filter { 1 } prepend . ;
 
MAIN: main
</lang>
{{out}}
<pre>
Line 1,961 ⟶ 2,269:
7777
9999
...
851851
857143
961038
994708
999999
}
Count of Kaprekar numbers <= 1,000,000: 54
</pre>
 
=={{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,984 ⟶ 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,025 ⟶ 2,340:
if (printnums .eqv. .false.) write(*, "(i0)") c
end subroutine
end program</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,046 ⟶ 2,361:
 
54</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-12-2016
' compile with: fbc -s console
 
Line 2,111 ⟶ 2,427:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 2,133 ⟶ 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,245 ⟶ 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,322 ⟶ 2,816:
str, sq, sq[:split], sq[split:]) // optional extra extra credit
}
}</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10000:
Line 2,404 ⟶ 2,898:
22803040 g10645 f2fcde0f1a78 f2fcde + 0f1a78
24137568 gggggg gggggf000001 gggggf + 000001</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">class Kaprekar {
private static String[] splitAt(String str, int idx) {
String[] ans = new String[2]
ans[0] = str.substring(0, idx)
if (ans[0] == "") ans[0] = "0" //parsing "" throws an exception
ans[1] = str.substring(idx)
return ans
}
 
static void main(String[] args) {
int count = 0
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10
for (long i = 1; i <= 1000000; i++) {
String sqrStr = Long.toString(i * i, base)
for (int j = 0; j < sqrStr.length() / 2 + 1; j++) {
String[] parts = splitAt(sqrStr, j)
if (parts[1] == "") continue
long firstNum = Long.parseLong(parts[0], base)
long secNum = Long.parseLong(parts[1], base)
//if the right part is all zeroes, then it will be forever, so break
if (secNum == 0) break
if (firstNum + secNum == i) {
System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1])
count++
break
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base " + base)
}
}</syntaxhighlight>
{{out}}
<pre>1 1 1 0 + 1
9 9 81 8 + 1
45 45 2025 20 + 25
55 55 3025 30 + 25
99 99 9801 98 + 01
297 297 88209 88 + 209
703 703 494209 494 + 209
999 999 998001 998 + 001
2223 2223 4941729 494 + 1729
2728 2728 7441984 744 + 1984
4879 4879 23804641 238 + 04641
4950 4950 24502500 2450 + 2500
5050 5050 25502500 2550 + 2500
5292 5292 28005264 28 + 005264
7272 7272 52881984 5288 + 1984
7777 7777 60481729 6048 + 1729
9999 9999 99980001 9998 + 0001
17344 17344 300814336 3008 + 14336
22222 22222 493817284 4938 + 17284
38962 38962 1518037444 1518 + 037444
77778 77778 6049417284 60494 + 17284
82656 82656 6832014336 68320 + 14336
95121 95121 9048004641 90480 + 04641
99999 99999 9999800001 99998 + 00001
142857 142857 20408122449 20408 + 122449
148149 148149 21948126201 21948 + 126201
181819 181819 33058148761 33058 + 148761
187110 187110 35010152100 35010 + 152100
208495 208495 43470165025 43470 + 165025
318682 318682 101558217124 101558 + 217124
329967 329967 108878221089 108878 + 221089
351352 351352 123448227904 123448 + 227904
356643 356643 127194229449 127194 + 229449
390313 390313 152344237969 152344 + 237969
461539 461539 213018248521 213018 + 248521
466830 466830 217930248900 217930 + 248900
499500 499500 249500250000 249500 + 250000
500500 500500 250500250000 250500 + 250000
533170 533170 284270248900 284270 + 248900
538461 538461 289940248521 289940 + 248521
609687 609687 371718237969 371718 + 237969
627615 627615 393900588225 39390 + 0588225
643357 643357 413908229449 413908 + 229449
648648 648648 420744227904 420744 + 227904
670033 670033 448944221089 448944 + 221089
681318 681318 464194217124 464194 + 217124
791505 791505 626480165025 626480 + 165025
812890 812890 660790152100 660790 + 152100
818181 818181 669420148761 669420 + 148761
851851 851851 725650126201 725650 + 126201
857143 857143 734694122449 734694 + 122449
961038 961038 923594037444 923594 + 037444
994708 994708 989444005264 989444 + 005264
999999 999999 999998000001 999998 + 000001
54 Kaprekar numbers < 1000000 (base 10) in base 10</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Text.Printf (printf)
import Data.Maybe (mapMaybe)
import Numeric (showIntAtBase)
Line 2,447 ⟶ 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,501 ⟶ 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,550 ⟶ 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,564 ⟶ 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,588 ⟶ 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,650 ⟶ 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,704 ⟶ 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,747 ⟶ 3,331:
266224 33334 a2c52a07g a2c5 + 2a07g
24 Kaprekar numbers < 1000000 (base 10) in base 17</pre>
 
=={{header|JavaScript}}==
'''This string version'''
<langsyntaxhighlight JavaScriptlang="javascript">function isKaprekar( n, bs ) {
if ( n < 1 ) return false
if ( n == 1 ) return true
Line 2,760 ⟶ 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,772 ⟶ 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,785 ⟶ 3,370:
kaprekar( 1, 255, 16)
kaprekar( 1, 255, 16, 16)
kaprekar( 1, 288, 17, 17)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,807 ⟶ 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,838 ⟶ 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|01.62}}
 
<langsyntaxhighlight lang="julia">function iskaprekar(n::Integer)
strn == dec(n1 && ^return 2)true
iftest(a, b) = n == 1a + b && b return true0
str = string(n^2)
else
return any(n == test(parse(Int, str[1:i]) +, parse(Int, str[i+1:end])) &&for parse(Int,i = str[i+1:end]length(str)-1) != 0
for i = 1:length(str)-1)
end
end
 
@show filter(iskaprekar, 1:10000)
@show count(iskaprekar, 1:10000)</langsyntaxhighlight>
 
{{out}}
Line 2,865 ⟶ 3,448:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.lang.Long.parseLong
import java.lang.Long.toString
 
Line 2,899 ⟶ 3,482:
}
println("$count Kaprekar numbers < $max (base 10) in base $base")
}</langsyntaxhighlight>
{{out}}
<pre> 1 1 1 0 + 1
Line 2,958 ⟶ 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 2,977 ⟶ 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,012 ⟶ 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
There are 54 Kaprekar numbers under one million.</pre>
 
 
=={{header|Maple}}==
<lang Maple>
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">
 
isKaprekar := proc(n::posint)
local holder, square, num_of_digits, k, left, right;
holder := true;
if n = 1 then
returnholder := true;
else
holder := false;
Line 3,038 ⟶ 3,620:
end if;
end do;
end if;
return holder;
end if;
end proc;
 
Line 3,047 ⟶ 3,629:
 
showKaprekar(10000);
countKaprekar(1000000);</langsyntaxhighlight>
 
{{out}}
Line 3,053 ⟶ 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,094 ⟶ 3,672:
 
length(%);
54</langsyntaxhighlight>
 
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">local
val base = 10;
fun kaprekar
Line 3,132 ⟶ 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,142 ⟶ 3,720:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Kaprekar;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
Line 3,204 ⟶ 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,224 ⟶ 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,245 ⟶ 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,255 ⟶ 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,271 ⟶ 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,282 ⟶ 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,298 ⟶ 3,877:
printf "Kaprekar numbers <= 10^%2d: %5d\n",
$n, scalar(grep { $_ <= $np } @kap);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,311 ⟶ 3,890:
Kaprekar numbers <= 10^14: 316
</pre>
 
=={{header|Perl 6}}==
===String version (slow)===
<lang perl6>sub kaprekar( Int $n ) {
my $sq = $n ** 2;
for 0 ^..^ $sq.chars -> $i {
my $x = +$sq.substr(0, $i);
my $y = +$sq.substr($i) || return;
return True if $x + $y == $n;
}
False;
}
 
print 1;
print " $_" if .&kaprekar for ^10000;
print "\n";</lang>
{{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. <lang perl6>sub kaprekar( Int $n, Int :$base = 10 ) {
my $hi = $n ** 2;
my $lo = 0;
loop (my $s = 1; $hi; $s *= $base) {
$lo += ($hi % $base) * $s;
$hi div= $base;
return $hi,$lo if $lo + $hi == $n and $lo;
}
();
}
 
print " $_" if .&kaprekar for ^10_000;
 
my $n;
(^1_000_000).race.map: { $n++ if kaprekar $_ }
say "\n\nBase 10 Kaprekar numbers < :10<1_000_000> = $n";
 
say "\nBase 17 Kaprekar numbers < :17<1_000_000>";
 
my &k17 = &kaprekar.assuming(:base(17));
 
my @results;
(^:17<1_000_000>).race.map: -> $n {
my ($h,$l) = k17 $n;
next unless $l;
my $n17 = $n.base(17);
my $s17 = ($n * $n).base(17);
my $h17 = $h.base(17);
@results.push: "$n $n17 $s17 ($h17 + $s17.substr(* - max(1,($s17.chars - $h17.chars))))";
}
 
.say for @results.sort({$^a.chars <=> $^b.chars});</lang>
{{out}}
<pre style="height:35ex">1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
 
Base 10 Kaprekar numbers < :10<1_000_000> = 54
 
Base 17 Kaprekar numbers < :17<1_000_000>
1 1 1 (0 + 1)
16 G F1 (F + 1)
64 3D E2G (E + 2G)
225 D4 A52G (A5 + 2G)
288 GG GF01 (GF + 01)
1536 556 1B43B2 (1B4 + 3B2)
3377 BBB 8093B2 (809 + 3B2)
4912 GGG GGF001 (GGF + 001)
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 + 0001)
266224 33334 A2C52A07G (A2C5 + 2A07G)
1153633 DDDDD B3D5E2A07G (B3D5E + 2A07G)
1334529 FGACC F0540F1A78 (F054 + 0F1A78)
1419856 GGGGG GGGGF00001 (GGGGF + 00001)
1787968 146FCA 19G4C12DG7F (19G4C + 12DG7F)
3122497 236985 4E3BE1F95D8 (4E3BE + 1F95D8)
3773952 2B32B3 711CB2420F9 (711CB + 2420F9)
4243968 2GDE03 8FEGB27EG09 (8FEGB + 27EG09)
5108481 3A2D6F CG10B2E3C64 (CG10B + 2E3C64)
5561920 3FA16D F5EAE3043CG (F5EAE + 3043CG)
6031936 443CCD 110DDE332FFG (110DDE + 332FFG)
6896449 4E9C28 16A10C37GB1D (16A10C + 37GB1D)
7435233 54067B 1A72G93AA382 (1A72G9 + 3AA382)
8017920 5AGGB6 1EF1D43D1EF2 (1EF1D4 + 3D1EF2)
9223201 687534 2835C5403G7G (2835C5 + 403G7G)
9805888 6F6F6G 2DBE3F41C131 (2DBE3F + 41C131)
11140416 7E692A 3A997C43DGBF (3A997C + 43DGBF)
11209185 7F391E 3B58D543F059 (3B58D5 + 43F059)
12928384 91D7F3 4EF79B43F059 (4EF79B + 43F059)
12997153 92A7E7 4FD82943DGBF (4FD829 + 43DGBF)
14331681 A1A1A1 5GF07041C131 (5GF070 + 41C131)
14914368 A89BDD 685C5E403G7G (685C5E + 403G7G)
16119649 B6005B 79F2793D1EF2 (79F279 + 3D1EF2)
16702336 BCGA96 8267143AA382 (826714 + 3AA382)
17241120 C274E9 8B7ACD37GB1D (8B7ACD + 37GB1D)
18105633 CCD444 99A555332FFG (99A555 + 332FFG)
18575649 D16FA4 A12BE53043CG (A12BE5 + 3043CG)
19029088 D6E3A2 A9A83F2E3C64 (A9A83F + 2E3C64)
19893601 E032GE B953G527EG09 (B953G5 + 27EG09)
20363617 E5DE5E C1BD752420F9 (C1BD75 + 2420F9)
21015072 EDA78C CF11C41F95D8 (CF11C4 + 1F95D8)
22349601 FCA147 E9D1D912DG7F (E9D1D9 + 12DG7F)
22803040 G10645 F2FCDE0F1A78 (F2FCDE + 0F1A78)
24137568 GGGGGG GGGGGF000001 (GGGGGF + 000001)</pre>
Note that this algorithm allows the null string on the left, taken as zero, which automatically includes 1 as the first element of the sequence.
 
===Casting out nines (fast)===
<lang perl6>sub kaprekar-generator( :$base = 10 ) {
my $base-m1 = $base - 1;
gather loop (my $place = 1; ; ++$place) {
my $nend = $base ** $place;
loop (my $n = $base ** ($place - 1); $n < $nend; ++$n) {
if $n * ($n - 1) %% $base-m1 {
my $pend = $place * 2;
loop (my $p = $place; $p < $pend; ++$p) {
my $B = $base ** $p;
my $lo = $n * ($B - $n) div ($B - 1);
my $hi = floor $n - $lo;
if $n * $n == $hi * $B + $lo and $lo {
take [$n, $hi, $lo];
last;
}
}
}
}
}
}
 
print " $_[0]" for kaprekar-generator() ...^ *.[0] >= 10_000;
say "\n";
 
say "Base 10 Kaprekar numbers < :10<1_000_000> = ", +(kaprekar-generator() ...^ *.[0] >= 1000000);
say '';
 
say "Base 17 Kaprekar numbers < :17<1_000_000>";
 
my &k17-gen = &kaprekar-generator.assuming(:base(17));
 
for k17-gen() ...^ *.[0] >= :17<1000000> -> @r {
my ($n,$h,$l) = @r;
my $n17 = $n.base(17);
my $s = $n * $n;
my $s17 = $s.base(17);
my $h17 = $h.base(17);
my $l17 = $l.base(17);
$l17 = '0' x ($s17.chars - $h17.chars - $l17.chars) ~ $l17;
say "$n $n17 $s17 ($h17 + $l17)";
}</lang>
(Same output.)
 
=={{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,542 ⟶ 3,965:
33334 squared a2c52a07g, split a2c5+2a07g
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">def FNkaprekar
var n
dup 2 power var s
s log int 1 + 10 swap power var t
true while
t 10 / var t
t n <= IF false else
s n - s t / int t 1 - * == IF false 1 var n else TRUE endif
endif
endwhile
n 1 ==
enddef
 
0
10000 FOR
dup FNkaprekar IF print " " print 1 + else drop endif
endfor
nl print " Kaprekar numbers" print</syntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">set_time_limit(300);
 
print_r(array_filter(range(1, 10000), 'isKaprekar'));
Line 3,561 ⟶ 4,004:
}
return false;
}</langsyntaxhighlight>
 
<pre>Array
Line 3,584 ⟶ 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,599 ⟶ 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,621 ⟶ 4,132:
 
end kaprekar;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,644 ⟶ 4,155:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Kaprekar ([int]$Number)
{
Line 3,670 ⟶ 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,677 ⟶ 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,696 ⟶ 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,708 ⟶ 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,722 ⟶ 4,233:
=={{header|PureBasic}}==
{{trans|C}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Kaprekar(n.i)
nn.q = n*n
tens.q= 1
Line 3,748 ⟶ 4,259:
Print("Press ENTER to exit")
Input()
EndIf</langsyntaxhighlight>
<pre> 1: 1
2: 9
Line 3,767 ⟶ 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,780 ⟶ 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,812 ⟶ 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,827 ⟶ 4,338:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 3,886 ⟶ 4,397:
</pre>
Other bases may be used e.g.:
<langsyntaxhighlight lang="python">
Base = 16
N = 4
Line 3,897 ⟶ 4,408:
Paddy_cnt += 1
break
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 3,943 ⟶ 4,454:
</pre>
 
=={{header|REXXQuackery}}==
 
<lang rexx>/*REXX pgm generates & counts (+ maybe shows) some Kaprekar #s using the cast─out─9 test*/
<syntaxhighlight lang="quackery"> [ dup 1 = if done
/*╔═══════════════════════════════════════════════════════════════════╗
dup temp put
║ Kaprekar numbers were thought of by the mathematician from India, ║
dup *
║ Shri Dattathreya Ramachardra Kaprekar (1905 ───► 1986). ║
false swap 1
╚═══════════════════════════════════════════════════════════════════╝*/
[ base share *
parse arg A B . /*obtain optional arguments from the CL*/
2dup /mod
if A=='' | A="," then A= 10000 /*Not specified? Then use the default.*/
over 0 = iff
if B=='' | B="," then B= -1000000 /* " " " " " " */
2drop done
call Kaprekar A /*gen Kaprekar numbers, show 'em*/
dup 0 = iff
call Kaprekar B /* " " " don't show 'em*/
2drop again
exit /*stick a fork in it, we're all done. */
+ temp share = iff
/*──────────────────────────────────────────────────────────────────────────────────────*/
[ rot not unrot ]
Kaprekar: procedure; parse arg N; #=0; aN=abs(N) /*set counter to zero; use │N│ value.*/
done
numeric digits max(9, 2*length(N) ) /*use enough decimal digits for square.*/
again ]
if aN>0 then call tell 1 /*unity is defined to be a Kaprekar #. */
2drop
/* [↑] handle case of N being unity.*/
temp release ] if aN>1 then dois j=9kaprekar ( forn aN-9;-> b s=j*j /*calculate the square of J (S). */
if j//9==s//9 then do k=1 for length(s)%2 /*≡ casted out 9's?*/
say "Kaprekar numbers less than one thousand: "
parse var s L +(k) R
[]
if j==L+R then do; call tell j; leave; end
1000 times
end /*k*/
[ i^ kaprekar if
end /*j*/
[ i^ join ] say]
echo cr cr
say center(" There're " # ' Kaprekar numbers below ' aN || ., 79, "═")
return
say "Number of Kaprekar numbers less than one million: "
/*──────────────────────────────────────────────────────────────────────────────────────*/
0
tell: #=#+1; if N>0 then say right(arg(1), digits()); return /*maybe display it*/</lang>
1000000 times
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> &nbsp; 10000 &nbsp; -1000000 </tt>}}
[ i^ kaprekar if 1+ ]
<pre>
echo cr cr
1
9
say "Base 17 Kaprekar numbers less than one million." cr cr
45
17 base put
55
99[]
1000000 times
297
[ i^ kaprekar 703if
[ i^ join ] 999]
say "In base 17: "
2223
dup echo cr
2728
base release
4879
say "In decimal: "
4950
echo</syntaxhighlight>
5050
 
5292
{{out}}
7272
 
7777
<pre>Kaprekar numbers less than one thousand.[ 1 9 45 55 99 297 703 999 ]
9999
 
Number of Kaprekar numbers less than one million: 54
═════════════════ There're 17 Kaprekar numbers below 10000.═════════════════
 
Base 17 Kaprekar numbers less than one million.
════════════════ There're 54 Kaprekar numbers below 1000000.════════════════
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,009 ⟶ 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)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
===String version (slow)===
<syntaxhighlight lang="raku" line>sub kaprekar( Int $n ) {
my $sq = $n ** 2;
for 0 ^..^ $sq.chars -> $i {
my $x = +$sq.substr(0, $i);
my $y = +$sq.substr($i) || return;
return True if $x + $y == $n;
}
False;
}
 
print 1;
print " $_" if .&kaprekar for ^10000;
print "\n";</syntaxhighlight>
{{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" line>sub kaprekar( Int $n, Int :$base = 10 ) {
my $hi = $n ** 2;
my $lo = 0;
loop (my $s = 1; $hi; $s *= $base) {
$lo += ($hi % $base) * $s;
$hi div= $base;
return $hi,$lo if $lo + $hi == $n and $lo;
}
();
}
 
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";
 
say "\nBase 17 Kaprekar numbers < :17<1_000_000>";
 
my &k17 = &kaprekar.assuming(:base(17));
 
my @results;
(^:17<1_000_000>).race.map: -> $n {
my ($h,$l) = k17 $n;
next unless $l;
my $n17 = $n.base(17);
my $s17 = ($n * $n).base(17);
my $h17 = $h.base(17);
@results.push: "$n $n17 $s17 ($h17 + $s17.substr(* - max(1,($s17.chars - $h17.chars))))";
}
 
.say for @results.sort: *.chars;</syntaxhighlight>
{{out}}
<pre style="height:35ex">1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
 
Base 10 Kaprekar numbers < :10<1_000_000> = 54
 
Base 17 Kaprekar numbers < :17<1_000_000>
1 1 1 (0 + 1)
16 G F1 (F + 1)
64 3D E2G (E + 2G)
225 D4 A52G (A5 + 2G)
288 GG GF01 (GF + 01)
1536 556 1B43B2 (1B4 + 3B2)
3377 BBB 8093B2 (809 + 3B2)
4912 GGG GGF001 (GGF + 001)
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 + 0001)
266224 33334 A2C52A07G (A2C5 + 2A07G)
1153633 DDDDD B3D5E2A07G (B3D5E + 2A07G)
1334529 FGACC F0540F1A78 (F054 + 0F1A78)
1419856 GGGGG GGGGF00001 (GGGGF + 00001)
1787968 146FCA 19G4C12DG7F (19G4C + 12DG7F)
3122497 236985 4E3BE1F95D8 (4E3BE + 1F95D8)
3773952 2B32B3 711CB2420F9 (711CB + 2420F9)
4243968 2GDE03 8FEGB27EG09 (8FEGB + 27EG09)
5108481 3A2D6F CG10B2E3C64 (CG10B + 2E3C64)
5561920 3FA16D F5EAE3043CG (F5EAE + 3043CG)
6031936 443CCD 110DDE332FFG (110DDE + 332FFG)
6896449 4E9C28 16A10C37GB1D (16A10C + 37GB1D)
7435233 54067B 1A72G93AA382 (1A72G9 + 3AA382)
8017920 5AGGB6 1EF1D43D1EF2 (1EF1D4 + 3D1EF2)
9223201 687534 2835C5403G7G (2835C5 + 403G7G)
9805888 6F6F6G 2DBE3F41C131 (2DBE3F + 41C131)
11140416 7E692A 3A997C43DGBF (3A997C + 43DGBF)
11209185 7F391E 3B58D543F059 (3B58D5 + 43F059)
12928384 91D7F3 4EF79B43F059 (4EF79B + 43F059)
12997153 92A7E7 4FD82943DGBF (4FD829 + 43DGBF)
14331681 A1A1A1 5GF07041C131 (5GF070 + 41C131)
14914368 A89BDD 685C5E403G7G (685C5E + 403G7G)
16119649 B6005B 79F2793D1EF2 (79F279 + 3D1EF2)
16702336 BCGA96 8267143AA382 (826714 + 3AA382)
17241120 C274E9 8B7ACD37GB1D (8B7ACD + 37GB1D)
18105633 CCD444 99A555332FFG (99A555 + 332FFG)
18575649 D16FA4 A12BE53043CG (A12BE5 + 3043CG)
19029088 D6E3A2 A9A83F2E3C64 (A9A83F + 2E3C64)
19893601 E032GE B953G527EG09 (B953G5 + 27EG09)
20363617 E5DE5E C1BD752420F9 (C1BD75 + 2420F9)
21015072 EDA78C CF11C41F95D8 (CF11C4 + 1F95D8)
22349601 FCA147 E9D1D912DG7F (E9D1D9 + 12DG7F)
22803040 G10645 F2FCDE0F1A78 (F2FCDE + 0F1A78)
24137568 GGGGGG GGGGGF000001 (GGGGGF + 000001)</pre>
Note that this algorithm allows the null string on the left, taken as zero, which automatically includes 1 as the first element of the sequence.
 
===Casting out nines (fast)===
<syntaxhighlight lang="raku" line>sub kaprekar-generator( :$base = 10 ) {
my $base-m1 = $base - 1;
gather loop (my $place = 1; ; ++$place) {
my $nend = $base ** $place;
loop (my $n = $base ** ($place - 1); $n < $nend; ++$n) {
if $n * ($n - 1) %% $base-m1 {
my $pend = $place * 2;
loop (my $p = $place; $p < $pend; ++$p) {
my $B = $base ** $p;
my $lo = $n * ($B - $n) div ($B - 1);
my $hi = floor $n - $lo;
if $n * $n == $hi * $B + $lo and $lo {
take [$n, $hi, $lo];
last;
}
}
}
}
}
}
 
print " $_[0]" for kaprekar-generator() ...^ *.[0] >= 10_000;
say "\n";
 
say "Base 10 Kaprekar numbers < :10<1_000_000> = ", +(kaprekar-generator() ...^ *.[0] >= 1000000);
say '';
 
say "Base 17 Kaprekar numbers < :17<1_000_000>";
 
my &k17-gen = &kaprekar-generator.assuming(:base(17));
 
for k17-gen() ...^ *.[0] >= :17<1000000> -> @r {
my ($n,$h,$l) = @r;
my $n17 = $n.base(17);
my $s = $n * $n;
my $s17 = $s.base(17);
my $h17 = $h.base(17);
my $l17 = $l.base(17);
$l17 = '0' x ($s17.chars - $h17.chars - $l17.chars) ~ $l17;
say "$n $n17 $s17 ($h17 + $l17)";
}</syntaxhighlight>
(Same output.)
 
=={{header|REXX}}==
╔═══════════════════════════════════════════════════════════════════╗
║ Kaprekar 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 display 'em.*/
call Kaprekar B /* " " " don't " " */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Kaprekar: procedure; parse arg N; aN= abs(N) /*obtain the limit; use │N│ value. */
numeric digits max(9, 2 * length(aN) ) /*use enough decimal digits for square.*/
d= digits(); tell= N>0 /*set D to number of digits; 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). */
jc= j//9 /*JC: J modulo 9 (cast out nines). */
if jc >2 then iterate /*Is J mod 9 > two? Then skip this J.*/
s= j*j /*calculate the square of J (S). */
if jc==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 iterate
#= # + 1; if tell then say right(j, d); leave
end /*k*/
end /*j*/
say
say center(" There're " # ' Kaprekar numbers below ' aN" ", 79, "═")
return</syntaxhighlight>
{{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,034 ⟶ 4,763:
end
return (n = 1)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,043 ⟶ 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,078 ⟶ 4,856:
puts "%7s %5s %9s %s + %s" % [decimal, *result]
end
end</langsyntaxhighlight>
 
{{out}}
Line 4,129 ⟶ 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,135 ⟶ 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,149 ⟶ 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,187 ⟶ 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,293 ⟶ 5,071:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; auxiliary functions : range, filter
(define (range a b)
(let loop ((v '()) (i b))
Line 4,319 ⟶ 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,383 ⟶ 5,161:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,472 ⟶ 5,250:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var kapkapr = HashSet()
 
for n in (1..15) {
var npk = (10**n - 1)
npk.divisorsudivisors.each { |d|
var dp = npk/d
ifkapr << (is_coprime(dp, == 1 ? d : d*invmod(d, dp)) {
kap{ dp == 1 ? d : d*invmod(d, dp) } := 0 ++
}
}
}
 
varsay numskapr.grep ={ kap.keys.map{<= Num(_)1e4 }.sort
 
for n in (6 .. 14) {
var npk = (10**n - 1)
printf("Kaprekar numbers <= 10^%2d: %5d\n", n, numskapr.count_by { .<= npk })
}</langsyntaxhighlight>
 
{{out}}
<pre>
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Kaprekar numbers <= 10^ 6: 54
Kaprekar numbers <= 10^ 7: 62
Line 4,505 ⟶ 5,282:
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">kap,n = getkap(1000000)
> i, 1..n
<< kap[i]!<10000
Line 4,524 ⟶ 5,301:
<
<= kap,#.size(kap,1)
.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,548 ⟶ 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,572 ⟶ 5,349:
incr kcount [kaprekar $i]
}
puts "$kcount Kaprekar numbers less than 1000000"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,581 ⟶ 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,588 ⟶ 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,613 ⟶ 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,619 ⟶ 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,649 ⟶ 5,426:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
ReadOnly max As ULong = 1000000
Line 4,699 ⟶ 5,476:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Kaprekar numbers below 10000
Line 4,721 ⟶ 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,741 ⟶ 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
Number of Kaprekar numbers below 1000000: 54</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt, Conv
 
var kaprekar = Fn.new { |n, base|
var order = 0
if (n == 1) return [true, -1]
var nn = n * n
var power = 1
while (power <= nn) {
power = power * base
order = order + 1
}
power = (power/base).floor
order = order - 1
while (power > 1) {
var q = (nn/power).floor
var r = nn % power
if (q >= n) return [false, -1]
if (q + r == n) return [true, order]
order = order - 1
power = (power/base).floor
}
return [false, -1]
}
 
var max = 1e4
System.print("Kaprekar numbers < %(max):")
for (m in 0...max) {
var res = kaprekar.call(m, 10)
if (res[0]) Fmt.print("$6d", m)
}
 
max = 1e6
var count = 0
for (m in 0...max) {
var res = kaprekar.call(m, 10)
if (res[0]) count = count + 1
}
System.print("\nThere are %(count) Kaprekar numbers < %(max).")
 
var base = 17
var maxB = 1e6.toString
System.print("\nKaprekar numbers between 1 and %(maxB)(base %(base)):")
max = Conv.atoi(maxB, base)
Fmt.print("\n Base 10 Base $d Square Split", base)
for (m in 2...max) {
var res = kaprekar.call(m, base)
if (res[0]) {
var sq = Conv.itoa(m*m, base)
var str = Conv.itoa(m, base)
var split = sq.count - res[1]
Fmt.print("$8d $7s $12s $6s + $s", m, str, sq, sq[0...split], sq[split..-1])
}
}</syntaxhighlight>
 
{{out}}
<pre>
Kaprekar numbers < 10000:
1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999
 
There are 54 Kaprekar numbers < 1000000.
 
Kaprekar numbers between 1 and 1000000(base 17):
 
Base 10 Base 17 Square Split
16 g f1 f + 1
64 3d e2g e + 2g
225 d4 a52g a5 + 2g
288 gg gf01 gf + 01
1536 556 1b43b2 1b4 + 3b2
3377 bbb 8093b2 809 + 3b2
4912 ggg ggf001 ggf + 001
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 + 0001
266224 33334 a2c52a07g a2c5 + 2a07g
1153633 ddddd b3d5e2a07g b3d5e + 2a07g
1334529 fgacc f0540f1a78 f054 + 0f1a78
1419856 ggggg ggggf00001 ggggf + 00001
1787968 146fca 19g4c12dg7f 19g4c + 12dg7f
3122497 236985 4e3be1f95d8 4e3be + 1f95d8
3773952 2b32b3 711cb2420f9 711cb + 2420f9
4243968 2gde03 8fegb27eg09 8fegb + 27eg09
5108481 3a2d6f cg10b2e3c64 cg10b + 2e3c64
5561920 3fa16d f5eae3043cg f5eae + 3043cg
6031936 443ccd 110dde332ffg 110dde + 332ffg
6896449 4e9c28 16a10c37gb1d 16a10c + 37gb1d
7435233 54067b 1a72g93aa382 1a72g9 + 3aa382
8017920 5aggb6 1ef1d43d1ef2 1ef1d4 + 3d1ef2
9223201 687534 2835c5403g7g 2835c5 + 403g7g
9805888 6f6f6g 2dbe3f41c131 2dbe3f + 41c131
11140416 7e692a 3a997c43dgbf 3a997c + 43dgbf
11209185 7f391e 3b58d543f059 3b58d5 + 43f059
12928384 91d7f3 4ef79b43f059 4ef79b + 43f059
12997153 92a7e7 4fd82943dgbf 4fd829 + 43dgbf
14331681 a1a1a1 5gf07041c131 5gf070 + 41c131
14914368 a89bdd 685c5e403g7g 685c5e + 403g7g
16119649 b6005b 79f2793d1ef2 79f279 + 3d1ef2
16702336 bcga96 8267143aa382 826714 + 3aa382
17241120 c274e9 8b7acd37gb1d 8b7acd + 37gb1d
18105633 ccd444 99a555332ffg 99a555 + 332ffg
18575649 d16fa4 a12be53043cg a12be5 + 3043cg
19029088 d6e3a2 a9a83f2e3c64 a9a83f + 2e3c64
19893601 e032ge b953g527eg09 b953g5 + 27eg09
20363617 e5de5e c1bd752420f9 c1bd75 + 2420f9
21015072 eda78c cf11c41f95d8 cf11c4 + 1f95d8
22349601 fca147 e9d1d912dg7f e9d1d9 + 12dg7f
22803040 g10645 f2fcde0f1a78 f2fcde + 0f1a78
24137568 gggggg gggggf000001 gggggf + 000001
</pre>
 
=={{header|XPL0}}==
Line 4,751 ⟶ 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 4,783 ⟶ 5,776:
[Text(0, " "); IntOut(0, N)];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,794 ⟶ 5,787:
=={{header|Yabasic}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">clear screen
n = 0
FOR i = 1 TO 999999
Line 4,816 ⟶ 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 4,830 ⟶ 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 4,840 ⟶ 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>
1,983

edits