Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. # A Kaprekar number is a number k with n-digits.
  2. # If you square k and add the right n digits to the left n or n-1 digits, the sum is k.
  3. # 9 and 297 are Kaprekar numbers.
  4. # 9 ^ 2 = 81 and 8 + 1 = 9.
  5. # 297 ^ 2 = 88209 and 88 + 209 = 297.
  6.  
  7. def kaprekar?(k)
  8. no_of_digits = k.to_s.size
  9. square = (k ** 2).to_s
  10.  
  11. second_half = square[-no_of_digits..-1]
  12. first_half = square.size.even? ? square[0..no_of_digits-1] : square[0..no_of_digits-2]
  13.  
  14. if (k == first_half.to_i + second_half.to_i)
  15. puts "#{k} is a kaprekar"
  16. else
  17. puts "#{k} is not a kaprekar"
  18. end
  19. end
  20.  
  21. puts "Enter a number"
  22. k = gets.to_i
  23.  
  24. kaprekar?(k)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement