Today I was introduced to the Kaprekar number and decided to check if a given number is a kaprekar one.
Here is what I got:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
number = ARGV[0].to_i | |
size = number.to_s.size | |
square = (number**2).to_s | |
first_half = square.size.even? ? square[0..size-1] : square[0..size-2] | |
second_half = square[-size..-1] | |
if number == first_half.to_i + second_half.to_i || square.size == 1 && number == square.to_i | |
puts "#{number} is a Kaprecar number" | |
else | |
puts "#{number} is NOT a Kaprecar number" | |
end |
To make it run simply:
ruby kaprekar.rb n
Now, be a good person a hug the person next to you =)
No comments:
Post a Comment