1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#!/usr/bin/env ruby
$VERBOSE=true
# In mathematics, a non-negative integer is called a "Kaprekar number" for a given base if the
# representation of its square in that base can be split into two parts that add up to the original
# number, with the proviso that the part formed from the low-order digits of the square must be
# non-zero—although it is allowed to include leading zeroes. For instance,
# 45 is a Kaprekar number, because 452 = 2025 and 20 + 25 = 45. The number 1 is Kaprekar in every base, because 12 = 01 in any base, and 0 + 1 = 1.
# Find all Kaprekar from 0 to 9999
# A function to test for Kaprekar. Requires n's square to be at least two digits.
def is_kap? n
s = (n*n).to_s
# Try different 2-part string splits and test sum
found = false
1.upto(s.size-1) {|i|
one,two = s[0,i].to_i, s[i..-1].to_i
if one>n || two==0
break
end
if one+two == n
found=true
break
end
}
found
end
# 1 is also strangely Kaprekar because apparently its square can be represented "01" and split "0"+"1" #logic
arr = [1]
(4..9999).each {|n|
arr<<n if is_kap?(n)
}
p arr
# [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
|