Matthias Totschnig - 1 year ago 49

Ruby Question

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`

`def kaprekar?(k)`

k == k * k.to_s.chars.map(&:to_i).inject(:+)

end

Using this, I'm getting

`true`

`9`

`false`

`55`

`19`

`false`

`297`

`703`

`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

Answer Source

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.