Last active
September 15, 2017 19:46
-
-
Save Aravin/1898da9740f7046a500d413d84e4fcaf to your computer and use it in GitHub Desktop.
A ruby program to find Happy and Sad Numbers
This file contains hidden or 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
# method for finding happy or sad number | |
def happy_or_sad(input) | |
result = 0 | |
repeated_number = Hash.new(); | |
while(!repeated_number.has_key?(input)) | |
temp = 0 | |
repeated_number[input] = 0 | |
input.each do |i| | |
temp = temp + (i.to_i * i.to_i) | |
end | |
input = temp.to_s.split('') | |
result = temp | |
end | |
result == 1 ? "happy" : "sad" | |
end | |
# Getting input | |
print "Enter the number: " | |
input = gets.split('') | |
# Calling the method | |
happy_or_sad(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment