Matthias Totschnig - 4 months ago 16
Ruby Question

# Error in ruby for RubyMonk: Kaprekar's number

I'm following the course at RubyMonk and I'm stuck on this problem:

9 is a Kaprekar number since: 9 ^ 2 = 81 and 8 + 1 = 9.

Find if a given number is a Kaprekar number

Using this, I keep getting
`false`
with each number:

``````def kaprekar?(k)
k == k * k.to_s.chars.map(&:to_i).inject(:+)
end
``````

Using this, I'm getting
`true`
for
`9`
(expected), and
`false`
for
`55`
and
`19`
(expected), but also
`false`
for
`297`
and
`703`
(should be
`true`
).

``````def kaprekar?(k)
a = k * k
k == a.to_s.chars.map(&:to_i).inject(:+)
end
``````

Here's the RubyMonk solution

``````def kaprekar?(k)
no_of_digits = k.to_s.size
square = (k ** 2).to_s

second_half = square[-no_of_digits..-1]
first_half = square.size.even? ? square[0..no_of_digits-1] : square[0..no_of_digits-2]

k == first_half.to_i + second_half.to_i
end
``````

Try this:

``````def kaprekar?(k)
sq=k**2
k == [sq.to_s.slice(0..k.to_s.size-1),sq.to_s.slice(k.to_s.size..-1)].map(&:to_i).inject(:+)
end
``````

This will take the square of the number, slice it, add both the parts and will return true or false accordingly.

For k = 1, 9, 45, 55, 99, 297, 703,... it returns true while for others the value is false.

Source (Stackoverflow)