Kaprekar numbers: Difference between revisions
Added Easylang
(Kaprekar numbers en BASIC256) |
(Added Easylang) |
||
(25 intermediate revisions by 20 users not shown) | |||
Line 47:
* [[Casting out nines]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F k(n)
V n2 = String(Int64(n) ^ 2)
L(i) 0 .< n2.len
V a = I i > 0 {Int(n2[0 .< i])} E 0
V b = Int(n2[i ..])
I b != 0 & a + b == n
R 1B
R 0B
print((1..9999).filter(x -> k(x)))
print((1..999999).filter(x -> k(x)).len)</syntaxhighlight>
{{out}}
<pre>
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
54
</pre>
=={{header|360 Assembly}}==
{{trans|PL/I}}
<
KAPREKAR CSECT
USING KAPREKAR,R13 base register
Line 144 ⟶ 165:
PG DC CL80' ' buffer
YREGS
END KAPREKAR</
{{out}}
<pre>
Line 175 ⟶ 196:
so i chose base 17 (17 ** 6).
<
with Ada.Strings.Fixed;
Line 305 ⟶ 326:
end loop;
Ada.Text_IO.Put_Line (" Total:" & Integer'Image (Count));
end Kaprekar2;</
{{out}}
Line 314 ⟶ 335:
=={{header|ALGOL 68}}==
<
# returns TRUE if n is a Kaprekar number, FALSE otherwise #
Line 357 ⟶ 378:
print( ( newline ) );
print( ( "There are ", whole( k count, 0 ), " Kaprekar numbers below ", whole( max number, 0 ), newline ) )
</syntaxhighlight>
{{out}}
<pre>
Line 364 ⟶ 385:
There are 54 Kaprekar numbers below 1000000
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">k?: function [n][
n2: to :string n*n
loop 0..dec size n2 'i [
a: (i > 0)? -> to :integer slice n2 0 dec i -> 0
b: to :integer slice n2 i dec size n2
if and? b > 0 n = a + b -> return true
]
return false
]
loop 1..10000 'x [
if k? x -> print x
]</syntaxhighlight>
{{out}}
<pre>1
9
45
55
99
297
703
999
2223
2728
4879
4950
5050
5292
7272
7777
9999</pre>
=={{header|AutoHotkey}}==
Function:
<
Loop, % L + ( C := 0 ) {
S := ( N := A_Index ) ** 2
Line 381 ⟶ 438:
}
Return C " Kaprekar numbers in [1-" L "]:`n" SubStr(R,3)
}</
Usage:
<syntaxhighlight lang
{{out}}
<pre>17 Kaprekar numbers in [1-10000]:
Line 389 ⟶ 446:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f KAPREKAR_NUMBERS.AWK
BEGIN {
Line 415 ⟶ 472:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 439 ⟶ 496:
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 498 ⟶ 555:
set /a tempcount+=1
goto lengthloop
</syntaxhighlight>
{{out}}
<pre>
Line 520 ⟶ 577:
</pre>
=={{header|BASIC}}==
==={{header|BASIC256}}===
<
for i = 1 to 1999999
if Kaprekar(i) then
Line 542 ⟶ 599:
until t <= n
return n = 1
end function</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
n% = 0
FOR i% = 1 TO 999999
Line 567 ⟶ 623:
IF s-n = INT(s/t)*(t-1) THEN = TRUE
UNTIL FALSE
= (n=1)</
{{out}}
<pre>
Line 598 ⟶ 654:
=={{header|Bracmat}}==
<
& 1:?count
& out$(!count 1)
Line 615 ⟶ 671:
)
& out$(str$("There are " !count " kaprekar numbers less than 1000000"))
);</
{{out}}
<pre>1 1
Line 637 ⟶ 693:
=={{header|Brat}}==
<
results = []
Line 663 ⟶ 719:
p "Number of Kaprekar numbers below 1,000,000:"
p kaprekar(1000000).length</
{{out}}
Line 675 ⟶ 731:
=={{header|C}}==
Sample for extra extra credit:
<
#include <stdint.h>
typedef uint64_t ulong;
Line 733 ⟶ 789:
return 0;
}</
{{out}}
<pre>base 10:
Line 782 ⟶ 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).
<
#include <stdlib.h>
#include <stdint.h>
Line 885 ⟶ 941:
return 0;
}</
=={{header|C sharp}}==
<
using System.Collections.Generic;
Line 950 ⟶ 1,006:
}
}</
{{out}}
Line 1,011 ⟶ 1,067:
=={{header|C++}}==
===Using String Manipulation (very slow)===
<
#include <string>
#include <iostream>
Line 1,064 ⟶ 1,120:
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}</
{{out}}
<pre>Kaprekar numbers up to 10000:
Line 1,098 ⟶ 1,154:
The code <code>"if ((k*(k-1))%(Base-1) == 0)"</code> is explained here: [[Casting out nines]].
<
// Generate Kaperkar Numbers
//
Line 1,121 ⟶ 1,177:
return 0;
}
</syntaxhighlight>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,178 ⟶ 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:
<
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>
Which produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,227 ⟶ 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
<
//
// Nigel Galloway. July 13th., 2012
Line 1,241 ⟶ 1,297:
const double nr = k*(B-k)/(B-1);
const int q = k-nr;
if
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;
}</
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,302 ⟶ 1,358:
54: 999999 is 999998 + 1 and squared is 999998000001. It is a member of Residual Set 0</pre>
Changing main:
<
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>
Produces:
<pre>1: 1 is 0 + 1 and squared is 1. It is a member of Residual Set 1
Line 1,348 ⟶ 1,404:
40: e6e6 is d042 + 16a4 and squared is d04216a4. It is a member of Residual Set a
41: ffff is fffe + 1 and squared is fffe0001. It is a member of Residual Set 0</pre>
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program assumes a 64-bit system.
% On a 32-bit system, the main task (show Kaprekar numbers < 10,000)
% will run correctly, but the extra credit part will crash with
% an overflow exception.
% Yield all positive splits of a number
splits = iter (n, base: int) yields (int,int)
step: int := base
while n >= step do
left: int := n / step
right: int := n // step
if left ~= 0 & right ~= 0 then
yield(left, right)
end
step := step * base
end
end splits
% Check whether a number is a Kaprekar number, and if so,
% return the proper split.
kap_split = struct[left, right: int]
maybe_kap = oneof[yes: kap_split, no: null]
kaprekar = proc (n, base: int) returns (maybe_kap)
for left, right: int in splits(n**2, base) do
if left + right = n then
return(maybe_kap$make_yes(
kap_split${left:left, right:right}))
end
end
return(maybe_kap$make_no(nil))
end kaprekar
% Format a number in a given base
to_base = proc (n, base: int) returns (string)
own digits: string := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n=0 then return("0") end
ds: array[char] := array[char]$[]
while n>0 do
array[char]$addl(ds,digits[n // base + 1])
n := n / base
end
return(string$ac2s(ds))
end to_base
% If a number is a Kaprekar number, show it, its square, and the split
display = proc (o: stream, n, base: int)
tagcase kaprekar(n, base)
tag yes (s: kap_split):
stream$putright(o, to_base(n, 10), 6)
if base ~= 10 then
stream$putright(o, to_base(n, base), 7)
end
stream$putright(o, to_base(n**2, base), 13)
stream$putl(o, " " ||
to_base(s.left, base) || " + " ||
to_base(s.right, base))
tag no:
end
end display
start_up = proc ()
po: stream := stream$primary_output()
% Find and output all the Kaprekar numbers under 10,000.
stream$putl(po, "Kaprekar numbers < 10,000:")
for i: int in int$from_to(1, 9999) do
display(po, i, 10)
end
% Count all the Kaprekar numbers under 1,000,000.
kaps: int := 0
for i: int in int$from_to(1, 999999) do
tagcase kaprekar(i, 10)
tag yes (s: kap_split): kaps := kaps + 1
tag no:
end
end
stream$putl(po, "\nThere are " || int$unparse(kaps) ||
" Kaprekar numbers under 1,000,000.\n")
% Find and output all base-17 Kaprekar numbers under 1,000,000.
stream$putl(po, "Base-17 Kaprekar numbers < 1,000,000:")
for i: int in int$from_to(1, 999999) do
display(po, i, 17)
end
end start_up</syntaxhighlight>
{{out}}
<pre>Kaprekar numbers < 10,000:
9 81 8 + 1
45 2025 20 + 25
55 3025 30 + 25
99 9801 98 + 1
297 88209 88 + 209
703 494209 494 + 209
999 998001 998 + 1
2223 4941729 494 + 1729
2728 7441984 744 + 1984
4879 23804641 238 + 4641
4950 24502500 2450 + 2500
5050 25502500 2550 + 2500
5292 28005264 28 + 5264
7272 52881984 5288 + 1984
7777 60481729 6048 + 1729
9999 99980001 9998 + 1
There are 53 Kaprekar numbers under 1,000,000.
Base-17 Kaprekar numbers < 1,000,000:
16 G F1 F + 1
64 3D E2G E + 2G
225 D4 A52G A5 + 2G
288 GG GF01 GF + 1
1536 556 1B43B2 1B4 + 3B2
3377 BBB 8093B2 809 + 3B2
4912 GGG GGF001 GGF + 1
7425 18BD 24E166G 24E + 166G
9280 1F1F 39B1B94 39B + 1B94
16705 36DB B992C42 B99 + 2C42
20736 43CD 10DE32FG 10DE + 32FG
30016 61EB 23593F92 2359 + 3F92
36801 785D 351E433G 351E + 433G
37440 7A96 37144382 3714 + 4382
46081 967B 52G94382 52G9 + 4382
46720 98B4 5575433G 5575 + 433G
53505 AF26 6GA43F92 6GA4 + 3F92
62785 CD44 9A5532FG 9A55 + 32FG
66816 DA36 AEG42C42 AEG4 + 2C42
74241 F1F2 D75F1B94 D75F + 1B94
76096 F854 E1F5166G E1F5 + 166G
83520 GGGG GGGF0001 GGGF + 1
266224 33334 A2C52A07G A2C5 + 2A07G</pre>
=={{header|CoffeeScript}}==
{{trans|Kotlin}}
<
ans = [ str.substring(0, idx), str.substring(idx) ]
if ans[0] == ""
Line 1,379 ⟶ 1,568:
console.log i, i.toString(base), s, p.join '+'
count++
console.log "#{count} Kaprekar numbers < #{max} (base 10) in base #{base}"</
{{out}}
<pre>1 '1' '1' '0+1'
Line 1,395 ⟶ 1,584:
=={{header|Common Lisp}}==
=== Fast solution using casting out nines filter ===
<
;; numbers n where n mod (base - 1) == n^2 mod (base - 1)
(defun res-list (base)
Line 1,436 ⟶ 1,625:
(terpri)
(ktest 1000000 17)
</syntaxhighlight>
{{out}}
<pre>
Line 1,460 ⟶ 1,649:
</pre>
===In the style of the C++ generator===
<
;; Generate Kaprekar Numbers using Casting Out Nines Generator
;;
Line 1,475 ⟶ 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>
{{out}}
<pre>
Line 1,622 ⟶ 1,811:
=={{header|D}}==
===Straightforward Version===
<
bool isKaprekar(in long n) pure /*nothrow*/ @safe
Line 1,645 ⟶ 1,834:
iota(1, 10_000).filter!isKaprekar.writeln;
iota(1, 1_000_000).count!isKaprekar.writeln;
}</
{{out}}
<pre>[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 1,652 ⟶ 1,841:
===Faster Version===
Right to left:
<
ulong powr = n ^^ 2UL;
ulong r, l, tens = 10;
Line 1,672 ⟶ 1,861:
if (i.isKaprekar)
writefln("%d: %d", count++, i);
}</
{{out}}
<pre>1: 1
Line 1,696 ⟶ 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}}==
<
import 'dart:math';
void main()
Line 1,750 ⟶ 2,011:
</syntaxhighlight>
=={{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}}
<
def check(n), do: check(n, 10)
Line 1,797 ⟶ 2,083:
:io.fwrite "~7w ~5s ~9s ~s + ~s~n", [n, Integer.to_string(n,base), a<>b, a, b]
end
end)</
{{out}}
Line 1,848 ⟶ 2,134:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-mode(compile).
-import(lists, [seq/2]).
Line 1,876 ⟶ 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>
{{out}}
<pre>
Line 1,887 ⟶ 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">
>function map kaprekarp (n) ...
$ m=n*n;
Line 1,904 ⟶ 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>
=={{header|F Sharp}}==
<syntaxhighlight lang="f sharp">
// Count digits in number
let digits x =
Line 1,944 ⟶ 2,230:
[1 .. 10000]
|> List.filter (float >> isKaprekar)
</syntaxhighlight>
=={{header|Factor}}==
This solution is based on the following Haskell code: [https://dev.to/heikodudzus/comment/1cl6].
<
math.ranges prettyprint sequences ;
Line 1,962 ⟶ 2,248:
1,000,000 [1,b] [ kaprekar? ] filter dup . length
"Count of Kaprekar numbers <= 1,000,000: " write .</
{{out}}
<pre>
Line 1,995 ⟶ 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.
<
\ Return nonzero if n is a Kaprekar number for tens, where tens is a
Line 2,013 ⟶ 2,299:
repeat
r> drop 1 = and ;
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 2,054 ⟶ 2,340:
if (printnums .eqv. .false.) write(*, "(i0)") c
end subroutine
end program</
{{out}}
<pre>1
Line 2,077 ⟶ 2,363:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,141 ⟶ 2,427:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>Kaprekar numbers below 10000
Line 2,163 ⟶ 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}}==
<
local a, b, p, q;
if n = 1 then
Line 2,275 ⟶ 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</
=={{header|Go}}==
Using the Ada interpretation of 1000000 base 17:
<
import (
Line 2,352 ⟶ 2,816:
str, sq, sq[:split], sq[split:]) // optional extra extra credit
}
}</
{{out}}
<pre>Kaprekar numbers < 10000:
Line 2,437 ⟶ 2,901:
=={{header|Groovy}}==
{{trans|Java}}
<
private static String[] splitAt(String str, int idx) {
String[] ans = new String[2]
Line 2,467 ⟶ 2,931:
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base " + base)
}
}</
{{out}}
<pre>1 1 1 0 + 1
Line 2,526 ⟶ 2,990:
=={{header|Haskell}}==
<
import Data.Maybe (mapMaybe)
import Numeric (showIntAtBase)
Line 2,567 ⟶ 3,031:
putStrLn ""
putStrLn $ heading 17
mapM_ (putStrLn . printKap 17) $ zip [1 ..] (kaprekars 17 1000000)</
{{out}}
<pre> # Value (base 10) Sum (base 10) Square
Line 2,621 ⟶ 3,085:
Generating Kaprekar numbers by factorizing b^n - 1:
<
import Data.List (group, nub, sort)
Line 2,670 ⟶ 3,134:
main :: IO ()
main = mapM_ print $ kaprekars 10 10000000</
=={{header|Icon}} and {{header|Unicon}}==
<
if ( n = 1 ) |
( n^2 ? ( n = move(1 to *&subject-1) + (0 ~= tab(0)) | fail )) then
Line 2,684 ⟶ 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</
{{out}}
Line 2,708 ⟶ 3,172:
=={{header|J}}==
'''Solution:'''
<
isKap=: 1 e. ] ((0 < {:"1@]) *. [ = +/"1@]) kapbase #: *:@]</
Example use:
<
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</
"Extra credit": (text representing numbers left in boxes for alignment purposes)
<syntaxhighlight 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,770 ⟶ 3,234:
├─────┼─────────┼─────┤
│33334│a2c52a07g│2a07g│
└─────┴─────────┴─────┘</
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.
<
isKapGroup=: [: +./"1 (((0 < {:"1@]) *. [ = +/"1@]) (kapbase@{: #:"2 0 ])@:*:)
6!:2 'a=.1, I. ([:; (<@isKapGroup/.~ 10<.@^.*:)) i.1e6'
12.3963
#a
54</
'''Alternative solution:'''
The following is a more naive, mechanical solution
<
allSplits=: (i.&.<:@# splitNum"0 1 ])@":
sumValidSplits=: +/"1@:(#~ 0 -.@e."1 ])
filterKaprekar=: #~ ] e."0 1 [: sumValidSplits@allSplits"0 *:</
Example use:
<
0 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
#filterKaprekar i. 1e6
54</
=={{header|Java}}==
<
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
Line 2,824 ⟶ 3,288:
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}</
{{out}} (base 10, shortened):
<pre>1 1 1 0 + 1
Line 2,870 ⟶ 3,334:
=={{header|JavaScript}}==
'''This string version'''
<
if ( n < 1 ) return false
if ( n == 1 ) return true
Line 2,881 ⟶ 3,345:
}
return false
}</
'''or this numeric version'''
<
if ( n < 1 ) return false
if ( n == 1 ) return true
Line 2,893 ⟶ 3,357:
}
return false
}</
'''with'''
<
bs = bs || 10; pbs = pbs || 10
const toString = n => n.toString(pbs).toUpperCase()
Line 2,906 ⟶ 3,370:
kaprekar( 1, 255, 16)
kaprekar( 1, 255, 16, 16)
kaprekar( 1, 288, 17, 17)</
{{out}}
<pre>
Line 2,928 ⟶ 3,392:
=={{header|jq}}==
{{Works with|jq|1.4}}
<
def is_kaprekar:
# The helper function acts like a loop:
Line 2,959 ⟶ 3,423:
[ range(1;10000) | select( is_kaprekar ) ],
count( range(1;1000000); is_kaprekar )
;</
{{Out}}
<
[1,9,45,55,99,297,703,999,2223,2728,4879,4950,5050,5292,7272,7777,9999]
54</
=={{header|Julia}}==
{{works with|Julia|1.2}}
<
n == 1 && return true
test(a, b) = n == a + b && b ≠ 0
Line 2,976 ⟶ 3,440:
@show filter(iskaprekar, 1:10000)
@show count(iskaprekar, 1:10000)</
{{out}}
Line 2,984 ⟶ 3,448:
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.lang.Long.toString
Line 3,018 ⟶ 3,482:
}
println("$count Kaprekar numbers < $max (base 10) in base $base")
}</
{{out}}
<pre> 1 1 1 0 + 1
Line 3,077 ⟶ 3,541:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
For i = 1 To 10000 '1000000 - Changing to one million takes a long time to complete!!!!
Line 3,096 ⟶ 3,560:
Next i
End Function
</syntaxhighlight>
=={{header|Lua}}==
<
function numLength (n)
local length = 0
Line 3,131 ⟶ 3,595:
if isKaprekar(n) then count = count + 1 end
end
print("\nThere are " .. count .. " Kaprekar numbers under one million.")</
{{out}}
<pre>1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
Line 3,139 ⟶ 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">
isKaprekar := proc(n::posint)
local holder, square, num_of_digits, k, left, right;
Line 3,165 ⟶ 3,629:
showKaprekar(10000);
countKaprekar(1000000);</
{{out}}
Line 3,171 ⟶ 3,635:
54</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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>
{{out}}
<pre>{1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999}
54</pre>
=={{header|Maxima}}==
<
[p, q, a, b],
if n = 1 then true else (
Line 3,212 ⟶ 3,672:
length(%);
54</
=={{header|ML}}==
==={{header|mLite}}===
<
val base = 10;
fun kaprekar
Line 3,250 ⟶ 3,710:
| (num :: nums) = kaprekar_list (num :: nums, [])
end
;</
Generate and show all Kaprekar numbers less than 10,000.
<
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
<
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,260 ⟶ 3,720:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
Line 3,322 ⟶ 3,782:
ReadChar
END Kaprekar.</
=={{header|Nim}}==
<
proc k(n: int): bool =
let n2 = $(n.
for i in 0 ..
let a = if i > 0: parseBiggestInt n2[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)</
{{out}}
<pre>[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 3,342 ⟶ 3,803:
=={{header|PARI/GP}}==
<
my(D=10^d,DD,t,v=List());
for(n=D/10+1,D-1,
Line 3,363 ⟶ 3,824:
upTo(4)
v=upTo(6);v
#v</
{{out}}
<pre>%1 = [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
Line 3,373 ⟶ 3,834:
=={{header|Perl}}==
===Numeric with casting out nines (fast)===
<
my $k = shift;
return if $k*($k-1) % 9; # Fast return "casting out nines"
Line 3,389 ⟶ 3,850:
my @kaprekar;
isKap($_) && push @kaprekar,$_ for 1..1_000_000;
print "Kaprekar Numbers below 1000000: ", scalar(@kaprekar), "\n";</
{{out}}
<pre>
Line 3,400 ⟶ 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}}
<
my %kap;
Line 3,416 ⟶ 3,877:
printf "Kaprekar numbers <= 10^%2d: %5d\n",
$n, scalar(grep { $_ <= $np } @kap);
}</
{{out}}
<pre>
Line 3,431 ⟶ 3,892:
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span>
<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>
<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>
<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>
<span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<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>
<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>
<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>
<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>
<span style="color: #000000;">basen</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">base</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<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>
<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>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</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>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"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>
<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>
<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>
<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>
<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>
<span style="color: #004080;">string</span> <span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">si</span> <span style="color: #008080;">do</span>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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: #0000FF;">=</span> <span style="color: #000000;">num</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"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>
<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>
<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>
<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>
<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,503 ⟶ 3,967:
=={{header|Phixmonti}}==
<
var n
dup 2 power var s
Line 3,520 ⟶ 3,984:
dup FNkaprekar IF print " " print 1 + else drop endif
endfor
nl print " Kaprekar numbers" print</
=={{header|PHP}}==
<
print_r(array_filter(range(1, 10000), 'isKaprekar'));
Line 3,540 ⟶ 4,004:
}
return false;
}</
<pre>Array
Line 3,563 ⟶ 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}}==
<
(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) ) ) )</
{{out}}
<pre>: (filter kaprekar (range 1 10000))
Line 3,578 ⟶ 4,110:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
kaprekar: procedure options (main); /* 22 January 2012 */
declare i fixed decimal (9), j fixed binary;
Line 3,600 ⟶ 4,132:
end kaprekar;
</syntaxhighlight>
{{out}}
<pre>
Line 3,623 ⟶ 4,155:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Test-Kaprekar ([int]$Number)
{
Line 3,649 ⟶ 4,181:
return $false
}
</syntaxhighlight>
<syntaxhighlight 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,656 ⟶ 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>
{{Out}}
<pre>
Line 3,675 ⟶ 4,207:
=={{header|Prolog}}==
Works with SWI-Prolog, uses a list comprehension : [[List comprehensions#Prolog]]
<
split_number(Z, 10, X).
Line 3,687 ⟶ 4,219:
kaprekar(N, V) :-
V <- {X & X <- 1 .. N & ((Z is X * X, kaprekar_(Z, X)); X = 1) }.
</syntaxhighlight>
{{out}}
<pre> ?- kaprekar(1000, V).
Line 3,701 ⟶ 4,233:
=={{header|PureBasic}}==
{{trans|C}}
<
nn.q = n*n
tens.q= 1
Line 3,727 ⟶ 4,259:
Print("Press ENTER to exit")
Input()
EndIf</
<pre> 1: 1
2: 9
Line 3,746 ⟶ 4,278:
===Splitting strings in a loop===
(Swap the commented return statement to return the split information).
<
n2 = str(n**2)
for i in range(len(n2)):
Line 3,759 ⟶ 4,291:
>>> len([x for x in range(1,1000000) if k(x)])
54
>>> </
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.
<
result = ""
while n:
Line 3,791 ⟶ 4,323:
print 'The number of Kaprekar Numbers found are',
print len(KNumbers)
raw_input()</
===Using Casting Out Nines Generator===
See: http://rosettacode.org/wiki/Casting_out_nines#Python for explanation and code for CastOut
<
Base = 10
N = 6
Line 3,806 ⟶ 4,338:
Paddy_cnt += 1
break
</syntaxhighlight>
Produces:
<pre>
Line 3,865 ⟶ 4,397:
</pre>
Other bases may be used e.g.:
<
Base = 16
N = 4
Line 3,876 ⟶ 4,408:
Paddy_cnt += 1
break
</syntaxhighlight>
Produces:
<pre>
Line 3,920 ⟶ 4,452:
40: e6e6
41: ffff
</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ dup 1 = if done
dup temp put
dup *
false swap 1
[ base share *
2dup /mod
over 0 = iff
2drop done
dup 0 = iff
2drop again
+ temp share = iff
[ rot not unrot ]
done
again ]
2drop
temp release ] is kaprekar ( n --> b )
say "Kaprekar numbers less than one thousand: "
[]
1000 times
[ i^ kaprekar if
[ i^ join ] ]
echo cr cr
say "Number of Kaprekar numbers less than one million: "
0
1000000 times
[ i^ kaprekar if 1+ ]
echo cr cr
say "Base 17 Kaprekar numbers less than one million." cr cr
17 base put
[]
1000000 times
[ i^ kaprekar if
[ i^ join ] ]
say "In base 17: "
dup echo cr
base release
say "In decimal: "
echo</syntaxhighlight>
{{out}}
<pre>Kaprekar numbers less than one thousand.[ 1 9 45 55 99 297 703 999 ]
Number of Kaprekar numbers less than one million: 54
Base 17 Kaprekar numbers less than one million.
In base 17: [ 1 G 3D D4 GG 556 BBB GGG 18BD 1F1F 36DB 43CD 61EB 785D 7A96 967B 98B4 AF26 CD44 DA36 F1F2 F854 GGGG 33334 ]
In decimal: [ 1 16 64 225 288 1536 3377 4912 7425 9280 16705 20736 30016 36801 37440 46081 46720 53505 62785 66816 74241 76096 83520 266224 ]
</pre>
=={{header|Racket}}==
<
#lang racket
(define (kaprekar? n)
Line 3,935 ⟶ 4,522:
(filter kaprekar? (range 1 10000))
</syntaxhighlight>
<pre>
'(1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999)
Line 3,943 ⟶ 4,530:
(formerly Perl 6)
===String version (slow)===
<syntaxhighlight lang="raku"
my $sq = $n ** 2;
for 0 ^..^ $sq.chars -> $i {
Line 3,955 ⟶ 4,542:
print 1;
print " $_" if .&kaprekar for ^10000;
print "\n";</
{{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"
my $hi = $n ** 2;
my $lo = 0;
Line 3,972 ⟶ 4,559:
print " $_" if .&kaprekar for ^10_000;
my atomicint $n;
(^1_000_000).race.map: { $n++ if kaprekar $_ }
say "\n\nBase 10 Kaprekar numbers < :10<1_000_000> = $n";
Line 3,990 ⟶ 4,577:
}
.say for @results.sort
{{out}}
<pre style="height:35ex">1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999
Line 4,057 ⟶ 4,644:
===Casting out nines (fast)===
<syntaxhighlight lang="raku"
my $base-m1 = $base - 1;
gather loop (my $place = 1; ; ++$place) {
Line 4,097 ⟶ 4,684:
$l17 = '0' x ($s17.chars - $h17.chars - $l17.chars) ~ $l17;
say "$n $n17 $s17 ($h17 + $l17)";
}</
(Same output.)
=={{header|REXX}}==
╔═══════════════════════════════════════════════════════════════════╗
║ Kaprekar numbers were thought of by the mathematician from India, ║
║ Shri Dattathreya Ramachardra Kaprekar (1905
╚═══════════════════════════════════════════════════════════════════╝
<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
call Kaprekar B /* " " "
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
Kaprekar: procedure; parse arg N;
numeric digits max(9, 2 * length(
#= 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
if jc >2 then iterate /*Is J mod 9 > two? Then skip this J.*/
s= j*j /*calculate the square of J (S). */
if
#= #
end /*k*/
end /*j*/
say
say center(" There're " # ' Kaprekar numbers below ' aN"
return</syntaxhighlight>
{{out|output|text= when using the default inputs of: <tt> 10000 -1000000 </tt>}}
<pre>
═════════════════ There're 17 Kaprekar numbers below 10000
════════════════ There're 54 Kaprekar numbers below 1000000
</pre>
=={{header|Ring}}==
<
nr = 0
for i = 1 to 200
Line 4,175 ⟶ 4,763:
end
return (n = 1)
</syntaxhighlight>
Output:
<pre>
Line 4,184 ⟶ 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
<
return [1, 1, 1, ""] if n == 1
return if n*(n-1) % (base-1) != 0 # casting out nine
Line 4,219 ⟶ 4,856:
puts "%7s %5s %9s %s + %s" % [decimal, *result]
end
end</
{{out}}
Line 4,270 ⟶ 4,907:
=={{header|Run BASIC}}==
<
x$ = str$(i * i)
if i = 1 then x$ = "10"
Line 4,276 ⟶ 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</
Kaprekar :8 + 1 = 9
Kaprekar :20 + 25 = 45
Line 4,290 ⟶ 4,927:
=={{header|Scala}}==
{{works with|Scala|2.9.1}}
<
def isKaprekar(n: Int, base: Int = 10):Option[Triple[String,String,String]] = {
Line 4,328 ⟶ 4,965:
println(k3.size + " Kaprekar numbers < 1000000 (b:10) for base 17"+"\n"*2)
}</
{{out}}
<pre style="height: 40ex; overflow: scroll">1
Line 4,434 ⟶ 5,071:
=={{header|Scheme}}==
<
(define (range a b)
(let loop ((v '()) (i b))
Line 4,460 ⟶ 5,097:
(filter kaprekar? (range 1 10000))
; (1 9 45 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999)</
=={{header|Seed7}}==
<
include "bigint.s7i";
Line 4,524 ⟶ 5,161:
end if;
end for;
end func;</
{{out}}
Line 4,613 ⟶ 5,250:
=={{header|Sidef}}==
{{trans|Perl}}
<
for n in (1..15) {
Line 4,628 ⟶ 5,265:
var k = (10**n - 1)
printf("Kaprekar numbers <= 10^%2d: %5d\n", n, kapr.count_by { .<= k })
}</
{{out}}
Line 4,645 ⟶ 5,282:
=={{header|SPL}}==
<
> i, 1..n
<< kap[i]!<10000
Line 4,664 ⟶ 5,301:
<
<= kap,#.size(kap,1)
.</
{{out}}
<pre>
Line 4,688 ⟶ 5,325:
=={{header|Tcl}}==
<
proc kaprekar n {
if {$n == 1} {return 1}
Line 4,712 ⟶ 5,349:
incr kcount [kaprekar $i]
}
puts "$kcount Kaprekar numbers less than 1000000"</
{{out}}
<pre>
Line 4,721 ⟶ 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.
<
#import nat
Line 4,728 ⟶ 5,365:
#cast %nLnX
t = ^|(~&,length) (iota; :/1+ ~&rFlS+ * ^/~& kd\%np ~&h+ %nP)~~/10000 1000000</
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,753 ⟶ 5,390:
</pre>
For the rest of the task, functions <code>p</code> and <code>r</code> are defined for numbers in base 17.
<
r = sum^|(~&,product/17)=>0+ *x -$/digits--'abcdefg' iota17
Line 4,759 ⟶ 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</
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,789 ⟶ 5,426:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<
ReadOnly max As ULong = 1000000
Line 4,839 ⟶ 5,476:
End Sub
End Module</
{{out}}
<pre>Kaprekar numbers below 10000
Line 4,861 ⟶ 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}}==
<
isKap &n [
@var s +'' *n n
Line 4,881 ⟶ 5,593:
!console.log "Number of Kaprekar numbers below 1000000: {#!-isKap @to 1M}"
]
}</
{{out}}
<pre>Kaprekar numbers below 10000: 1,9,45,55,99,297,703,999,2223,2728,4879,4950,5050,5292,7272,7777,9999
Line 4,889 ⟶ 5,601:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var kaprekar = Fn.new { |n, base|
Line 4,941 ⟶ 5,653:
Fmt.print("$8d $7s $12s $6s + $s", m, str, sq, sq[0...split], sq[split..-1])
}
}</
{{out}}
Line 5,032 ⟶ 5,744:
numbers up to 1,000,000. Floating point (double) provides 15 decimal digits of precision.
<
func Kaprekar(N, B); \Returns 'true' if N is a Kaprekar number in base B
Line 5,064 ⟶ 5,776:
[Text(0, " "); IntOut(0, N)];
CrLf(0);
]</
{{out}}
Line 5,075 ⟶ 5,787:
=={{header|Yabasic}}==
{{trans|BBC BASIC}}
<
n = 0
FOR i = 1 TO 999999
Line 5,097 ⟶ 5,809:
loop
return (n=1)
end sub</
=={{header|zkl}}==
{{trans|D}}
<
powr:=n*n;
r:=l:=0; tens:=b;
Line 5,111 ⟶ 5,823:
}
return(False);
}</
<
[1..].filter(T(isKaprekarB, fcn(n){ if(n>=10000) Void.Stop else True })));
Line 5,121 ⟶ 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..]);</
{{out}}
<pre>
|