Calculate n Kaprekar Numbers

Perl - 63 bytes

#!perl -l
map{1while$l=length++$_,$_**2=~/.{$l}$/,$`+$&^$_;print}($_)x<>

Counting the shebang as one byte. Input is taken from stdin.

This has an acceptable runtime for n ≤ 50, after that it gets a bit slow.

Sample usage:

$ echo 20 | perl kaprekar.pl
1
9
45
55
99
297
703
999
2223
2728
4950
5050
7272
7777
9999
17344
22222
77778
82656
95121

C, 109 106

long long i=1;x=10,n;main(){scanf("%d",&n);for(;n;x*=x<=++i?10:1)(i-i*i/x-i*i%x)||printf("%lld ",i,n--);}
  • with n up to 17 it would be ok to remove the long long,
  • The exceeding printf parameter is abused:)
  • Why it is not possible to use empty statement in the ternary operator? the two 1 are silly...
  • Thank to Josh for aditional 3 characters...

Mathematica 144 154

k@m_:=((x=m^2)-(w=FromDigits[Take[IntegerDigits@x,y=-IntegerLength@m]]))*10^y+w==m;
g@n_:=(s={};i=0;While[Length@s<n,If[k@i,s=Append[s,i]];i++];s)   

Test

g[14]

0
1
9
45
55
99
297
703
999
2223
2728
4950
5050
7272

Tags:

Code Golf