Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A Kaprekar number is a number k with n-digits.
- # If you square k and add the right n digits to the left n or n-1 digits, the sum is k.
- # 9 and 297 are Kaprekar numbers.
- # 9 ^ 2 = 81 and 8 + 1 = 9.
- # 297 ^ 2 = 88209 and 88 + 209 = 297.
- 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]
- if (k == first_half.to_i + second_half.to_i)
- puts "#{k} is a kaprekar"
- else
- puts "#{k} is not a kaprekar"
- end
- end
- puts "Enter a number"
- k = gets.to_i
- kaprekar?(k)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement