Last active
January 24, 2019 05:23
-
-
Save shankar524/ca3136c0ffb076f1fbf02f68e2fe63a1 to your computer and use it in GitHub Desktop.
This program finds if a number is a happy number or not.
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
#this function squares a number | |
def square(number) | |
number**2 | |
end | |
#this function breaks a number into its subsequent array | |
def break_number_to_arr(number) | |
return [0] if number.zero? | |
return_arr=[] | |
while number>0 | |
number,item = number.divmod 10 | |
return_arr.unshift item | |
end | |
return_arr | |
end | |
#this function tries to find if an number is happy number | |
def is_happy_number(number) | |
#this array stores the number obtained in each steps | |
visited_arr=[] | |
while(number!=1) | |
puts "INFO: Checking for #{number}" | |
temp_sum=0 | |
break_number_to_arr(number).each { |item| temp_sum+=square(item) } | |
number = temp_sum | |
#check if number is already visited | |
if(visited_arr.include? number) | |
return false | |
else | |
#add number to visited list | |
visited_arr << number | |
end | |
end | |
return true | |
end | |
#main program begins here | |
puts "Enter any number:" | |
begin | |
#typecast to integer | |
input =Integer(gets.chomp) | |
#check if input number is a happy number | |
if(is_happy_number(input)) | |
puts "#{input} is a happy Number. YAHOO" | |
else | |
puts "#{input} is not a happy Number." | |
end | |
#if error | |
rescue | |
puts "Please enter a valid Number." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment