I saw this tweet over the weekend—
Via Wikipedia—
In mathematics, a Kaprekar number for a given base is a non-negative integer, the representation of whose square in that base can be split into two parts—either or both of which may include leading zeroes—that add up to the original number. For instance, 45 is a Kaprekar number, because 452 = 2025 and 20 + 25 = 45.
Challenge
In the language of your choice, write a script to find the first 8 Kaprekar numbers. 1, 9, 45, 55, 99, 297, 703, 999
Two clarifications via @ripsup here:
First gotcha is the second part of the split numbers must be positive (no zeros). The second part was that you add a zero to the front if the length is odd.
Post your solution in the comments below!
Oldest comments (36)
I'm not pretty good at coding but I tried in my own way :) just for fun and I hope is ok.
Here is my JS version:
Here is the JSFiddle link:
jsfiddle.net/kw95nv45/2/
Pythonic mine's:
Usage:
python script.py maxmaxis the maximum integer to look up to (3037000499):Here is my Javascript version of Kaprekar numbers
This was a lot harder than I thought mainly because I had to look up why some numbers were and weren't Kaprekar numbers because the above description doesn't include all the details. First gotcha is the second part of the split numbers must be positive (no zeros). The second part was that you add a zero to the front if the length is odd.
And I already refactored my answer. I'm happier with this one.
Awesome job refactoring, and apologies for not including the pertinent info re: zeros in the OP!! I'll add that info to the main post.
Time to get my repl up and running. Not very clean, but gets the job done. Here's some Clojure:
Thanks to Richard Orelup' tip to zero-pad the number if its length is odd.
Taking inspiration from Thomas Much's answer, I refactored my code to be more functional-esque and idiomatic:
Something like this in python
Figure it's only fair to throw my answer into the ring. Clearly very novice and verbose 😇. Added a number of comments for the other #beginners out there.
Because I haven't done Groovy for a while. I miss it!
Ok, here's a Java 8 version:
As Heiko points out, the solution was incorrect, because the split was always done in the middle of the string...
So, here's a (hopefully correct) Java 9 solution (Java 9 because I use takeWhile):
I chose to output the first 16 numbers so we can see the output includes numbers 4879 and 5292.
I really like to see your use of Streams and lambdas solving this problem. Nice occasion for me to learn a little bit more about them.
For those a fan of Guile: