text:
Calculate n Kaprekar Numbers
A Kaprekar number is an n-digit number k that, when the first n or n-1 digits of k^2 are added to the second n the digits of N^2, the result is N.
Examples:
9^2 = 81.  8+1 = 9.
45^2 = 2025.  20+25 = 45.
297^2 = 88,209. 88+209 = 297

The Kaprekar sequence begins at 1.
Write a program that calculates and outputs the first n Kaprekar numbers, with n being in the range, but not limited to the range, of 1 to 100.  Each Kaprekar number must be separated with whitespace and nothing else.
More Kaprekar numbers can be found here to check your program against, but this resource MAY NOT be used in any way to help with the calculation - in other words, no hard-coding, reading from this source, or using it in any other exploitive way - all the numbers must be generated by your program.
Shortest code wins.

@devnull Is this better?  It means that the program must support an n up to at least 100.

MathWorld's definition conflicts with A006886 (MathWorld specifies that m is the length of the original number, A006886 specifies that it is at least that large). Your definition in the first paragraph is slightly different than both.

@primo OK, I get it now.  Will revise.

Ahh, you're right. They are equivalent statements. A note should be made that the two definitions are not identical, though. 4879 is the first counter example (the square is split 3:5, rather than 4:4).

@primo Is this better?  So the length of the number squared must be equal to twice the length of the number or twice the length of the number plus 1?

Your previous definition was more correct. A square of a number cannot have a length of 2n+1, where n is the length of the original number. The OEIS definition states that the right part is has length of at least n, and the left is the rest.

@primo Oops, my mistake again.

I think some confusion is being introduced by the fact that OEIS has more than one Kaprekar sequence. This is the one that represents the MathWorld definition: http://oeis.org/A053816

@JonathanVanMatre Yes, I think so too.  Just like there are variants of the Fibonacci sequence (including the Lucas sequence).  I changed the link.

I should add that the one I just linked is not the one you are linking to. And also the Wikipedia article you link to espouses the A006886 definition, not the MathWorld one, so that may also end up leading people astray.

@JonathanVanMatre I removed the Wiki link and changed the A006886 link to the A053816 link.

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

No problem about the runtime.  This is just code golf.

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...

If you only care about the false value, you can use boolean logic instead of a ternary statement.  Example, (i-i*i/x-i*i%x)||printf(...).

You can also initialize x and i at the global scope instead of in the for loop to save a couple chars.

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

Your output does not meet the criteria Each Kaprekar number must be separated with whitespace and nothing else.

RononDex.  I adjusted the output.

Javascript 96
for(i=0,n=prompt(s='');n;i++){t=''+i*i;if(t.substr(0,l=t.length/2)==i-t.substr(l))n--,s+=i+' '}s

Output :
0 1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643 390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033 681318 791505 812890 818181 851851 857143 961038 994708 999999

The input specifies the number of values to output, and not the maximum value.

missed that, fixed !

96: for(i=0,n=prompt(s='');n;i++){t=''+i*i;if(t.substr(0,l=t.length/2)==i-t.substr(l))n--,s+=i+' '}s

Bien joué Florent :)

Why don't you store the values in an array and simply join them?

Because it would be probably longer.

python - 98
I used some nice python slicing to shave a few characters off.
i=n=0
while n<20:
 i+=1;s=str(i**2);l=-len(str(i))
 if int("0"+s[:l])+int(s[l:])==i:print(i);n+=1

Nice job.  I ran out of votes for today, but I will upvote it in a hour.

C# - 255 Characters.
int x=100;decimal k=0;while(x>0){k++;decimal d=k*k;string s=d.ToString("n").Replace(",","").Split('.')[0];int g=k.ToString().Length;int h=s.Length;if(k==d||(h!=g&&long.Parse(s.Substring(h-g))+long.Parse(s.Substring(0,h-g))==k)){Console.Write(k+" ");x--;}}

x is the number of Kaprekar numbers you wish the code to find. This has been tested in the range of 1 to 100 but should support a lot more than this. 100 numbers took two and a quarter hours to return although the first 50 only took about 1 second - things slowed down gradually after that.
Output:
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778
82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643
390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033
681318 791505 812890 818181 851851 857143 961038 994708 999999 4444444 4927941
5072059 5555556 9372385 9999999 11111112 13641364 16590564 19273023 19773073
24752475 25252525 30884184 36363636 38883889 44363341 44525548 49995000 50005000
55474452 55636659 61116111 63636364 69115816 74747475 75247525 80226927 80726977
83409436 86358636 88888888 91838088 94520547 99999999 234567901 332999667
432432432 567567568 667000333 765432099 999999999 1111111111 1776299581 2020202020
3846956652 3888938889 4090859091 4132841328 4756047561

Laid out this code is as follows;
        int x = 100;
        decimal k = 0;
        while (x > 0)
        {
            k++;
            decimal d = k * k;
            string s = d.ToString("n").Replace(",", "").Split('.')[0];
            int g = k.ToString().Length;
            int h = s.Length;

            if (k == d || (h != g && long.Parse(s.Substring(h - g)) + long.Parse(s.Substring(0, h - g)) == k) )
            {
                Console.Write(k + " "); x--;
            }
        }

I'd love to know if this can be shortened further.

C, 90 76 75 bytes
long long d,r=1;k(n){for(;++d/r?r*=10:--n;d-d*d/r-d*d%r||printf("%d ",d));}

R, 99 characters
k=n=0;N=scan();while(n<N){k=k+1;j=k^2;i=10^ceiling(nchar(j)/2);if(k==j%/%i+j%%i){cat(k," ");n=n+1}}

With i being half the number of digits of k^2 rounded up, the evaluation of wether k is a Kaprekar number is performed here by adding the quotient and the remainder of the integer division of k^2 by 10^i (the quotient being the left half of the digits rounded down and the remainder the right half rounded up).

Python 2.7, 144 (including newlines)
def c(c):
 l="1";i=2;u=1
 while u<c:
  r=str(i**2);w=len(r)
  if w>1:
   if i==int(r[:w/2])+int(r[w/2:]):
    l+=" "+str(i);u+=1
  i+=1
 print l

Output for c = 10:
1 9 45 55 99 297 703 999 2223 2728

Output for u = 20:
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121

Whoops! Fixed that now. Slightly longer, but correct. I discovered semicolons in Python! Hurrah!

Then this will blow your mind: line 7 can go at the end of the previous line.

... Oh. Ah damn. Oh well. Still pretty good for something I knocked together during my lunch break, considering that my knowledge of Python is meagre at best.

bash+sed, 75 characters
Bash does integer-only arithmetic and represents numbers as decimal strings; these attributes are helpful for golfing this challenge.  Also undeclared/unassigned variables are assumed to have a value of 0 when doing arithmetic.
for((;s=++i*i,l=${#s}/2,1;));{
((${s:0:l}+10#${s:l}-i))||echo $i
}|sed $1q

It irked me to put the 10# in there, but something like this is necessary if the second half of the split starts with a 0.  When doing arithmetic, bash treats such numbers as octal, unless the base is explicitly stated.

$ ./kaprekar.sh 10
1
9
45
55
99
297
703
999
2223
2728
$

Python 3.3 - 117 characters
n=int(input())
p=1
while n>0:
    v=str(p**2)
    l=len(v)
    if p==int(v[l//2:])+int('0'+v[:l//2]):
        print(p)
        n-=1
    p+=1

Each level of indentation,  and each newline except the final one, all count for 1 character. I think that is fair for Python code. The script expects the user to input the number of Kaprekar numbers to compute.

 J - 64
Kinda ugly, but still. It checks all numbers up to one million then takes n of them, so it works only for n<=50.
n{.}.I.(]=+/&;&:(10&#.&.>)&(<.@-:@#({.;}.)])&(10&#.inv@*:))i.1e6

n is where to put the input

In the spec, it said to calculate up to 100 of them.  It probably wouldn't add that many characters to add another variable solely for counting the number of Kaprekar numbers found.


text:
Crash IRB (interactive Ruby)
Ruby comes with a built-in REPL, which is quite handy.

Your challenge is to crash it in the least amount of code!
The definition of "crash" is "make it exit in an unintended way." This means exit, quit, abort, irb_exit, irb_quit, et. al. are not valid answers.
Furthermore, you may not cause any side-effect to any other part of the system. For example, `rm -rf /` is not valid either.
Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer.
The final restriction is that you may not rely on any gems.
This is code-golf, so the shortest code that crashes IRB will win!

I can haz golfscript anser, plz?

wow. i don't know ruby, and after reading these answers i'll never learn it.

"The definition of 'crash' is 'make it exit in an unintended way.'" How are we supposed to write code intended to do something unintended? I vote to close as unclear what you're asking.

5 characters
ENV=0

(inspired by @daniero's answer)

doesn't work for me: irb(main):001:0> ENV=0 (irb):1: warning: already initialized constant ENV

@BrianMinton Had only a 1.9.3p194 at hand and it "works" with that version.

ah, my version is quite old: irb 0.9.6(09/06/30)

@BrianMinton that is the latest version of irb

16 characters
String=0
String=0

Not the shortest, but I think it's funny that it doesn't crash until the second line. Generates roughly 20 lines of text before IRB exits. For some reason it cannot be shortened to for instance 2.times{String=0}.

edit
Of all the answers so far, this is the only one that has worked for me (and it works in all versions I could get my hands on), and I've tested all of them in these versions:

On whatever kind of Linux I get when ssh'ing into my university:

ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
ruby 1.8.5 (2006-08-25) [x86_64-linux]

Mac OS X Mavericks default:

ruby 2.0.0p247 (2013-06-27 revision 41674) [universal.x86_64-darwin13]

Installed through Homebrew on OS X:

ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]

edit 2
7 characters
Combining my first version (and/or @Howard's answer, for maximum cross reference) with @chinese perl goth's answer:
STDIN=0

Array=0 crashes immediately.

@primo cool, but I can't get it to work :/ (See my edit)

Same here, only this and the closing stdin answer work, all the others give warnings only.

Yes, the stdin one works for me too. It was posted after my edit.

You can shorten the second line to = and it still crashes.

12 chars
ruby is not exactly my cup of tea, but I've just found out that irb acts funny when I close the stdin :)
$stdin.close

tested on irb 0.9.6(09/06/30) and ruby 1.9.3p194

STDIN.close works too, and it's 1 less char!

+1 because it's so obvious when you look at it that it will cause trouble :) My answer is probably more of a bug, but for this one you can't really expect IRB to do anything clever; it's like in Star Trek or whatever when they ask a super intelligent robot an impossible question and it explodes.

Related: $>.close.

10 9 chars
A shorter variant on @daniero's answer:
String=1
-

This works at least in the default OS X Mavericks Ruby (2.0.0).
The answer basically relies on the fact that the Ruby Token function does a case on the input token. One of the cases checks against String, which has been redefined by the first line. This case fails, so the case falls through to the default, which assumes the object has an ancestors accessor (which it does not).
Because the "bug" is in the tokenizer, the first line won't fail because the line only takes effect after the parsing is finished. Thus, it only affects subsequent lines. Subsequent lines must contain some kind of operator in order to see the failure.

+1 For the explanation. But who is this daneiro? ;)

@daniero: My apologies, I appear to be lysdexic today.

5 characters
$>=$<

Sets stdout to stdin which throws an error trying to open stdin for writing and crashes irb.

Note that this is tested on ruby 2.3.0p0

22 characters
def method_missing;end

Apparently it messes with some irb internals. (To fix it, add self. after def.)

12 characters
def send;end

As far as I know, there are four methods in the Object class which show this kind of behaviour:
send
method_missing
respond_to?
respond_to_missing?

In my IRB it simply returns nil and carries on

@daniero 1.8.6 and 1.9.3 both crash.

@primo no longer crashes on 2.0.0

5 Characters
IRB=0

Nothing disturbs IRB quite like redefining IRB.

Yeah! This doesn't crash, but prints 20 lines errors after anything!

Probably a different version of IRB now, @MegaMan so by now, definitely YMMV.

Both are cool, anyway!

12 10 characters
exec"exec"

I don't know if this counts, because of the exec

You can get rid of the space after the first exec

8 characters
Similar to chinese perl goth's answer:
$>.close

$> is an alias for STDOUT.

26 + 1 = 27 characters
This isn't very golfy, but I was amused to discover it by accident and thought others might enjoy it.
class Fixnum;def +;end end

I added +1 to the score because you have to press Enter a second time after entering the above (but not +2 because no one else counted Enter).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes