go ahead... be a heretic PerlMonks

[golf] Kaprekar Numbers

by jynx (Priest)
 on Jul 05, 2005 at 18:53 UTC Need Help??

It's been a while since i've done much Perl, or posted here, so please take a tetanus shot and bear with me, because i'm a little rusty. This might not be the most interesting problem, but i certainly had fun with it...

A Kaprekar number is one where if you square it and break it in half (the right side larger for oddly lengthed numbers), the two halves add up to the original number. This is only roughly the definition, you can go here for a longer layman's definition, and here for a rigorous definition.

One example Kaprekar number: 297
297**2 == 88,209.
88 + 209 == 297

Given a subroutine outline like so:
```sub kap_check {
...
}

the golf is to fill in the interesting bits that accept one numeric argument and return true or false depending on whether the input is a Kaprekar number or not. If you take a look at the rigorous page, you'll notice some strange numbers that don't fit in with the layman's definition above (like 4879). Ignore those numbers for the purpose of this golf.

My solution at 53 chars:
```#23456789_123456789_123456789_123456789_123456789_123456789_
\$_=\$_[0]*pop;\$==.5*length;/(.{\$=})(.*)/;\$1+\$2==\$_**.5
jynx

Replies are listed 'Best First'.
Re: [golf] Kaprekar Numbers
by thospel (Hermit) on Jul 05, 2005 at 20:20 UTC
Here's a 34 for the rigorous version:
```"@_"**2=~/(??{"@_"!=\$`+\$'&&a})/*\$'
(you can make it warning free at the cost of one more character)
Re: [golf] Kaprekar Numbers
by Roy Johnson (Monsignor) on Jul 05, 2005 at 19:47 UTC
41:
```\$_=\$_[0]**2;\$==y///c/2;/.{\$=}/;\$&+\$'==pop

Caution: Contents may have been coded under pressure.
Based on your idea, I got it to 38:
```# 34567890123456789012345678901234567890
\$_=\$_[0]**2;pos=y///c/2;//g;\$`+\$'==pop
(Edit: and using thospel's "@_" instead of \$_[0] makes it 37. I wonder how I managed to miss that...)
Like this it's 34:
```(pos=\$_="@_"**2)/=2;//g;\$`+\$'==pop

Create A New User
Node Status?
node history
Node Type: obfuscated [id://472564]
Approved by ktross
Front-paged by grinder
help
Chatterbox?
 [Corion]: 1nickt: No, I'm using it with Windows 10, but with the 4k display, yes. It's a very nice build IMO, and relatively sturdy. Also, it got 8 or 9 on the ifixit repair scale, which I consider good [Corion]: ... especially as I expect to have to replace the battery set in two or three years' time [1nickt]: Nice. So happy that Dells are still user-repairable. Unusual these days. [1nickt]: I will certainly not be buying any more Macs. [Corion]: 1nickt: Yeah, or at least, I hopoe so ;)

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (13)
As of 2017-03-27 13:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (320 votes). Check out past polls.