Strong number program in Ruby



Write a strong number program in Ruby

A number is called strong number if sum of the factorial of its digit is equal to number itself. For example: 145 since

1! + 4! + 5! = 1 + 24 + 120 = 145

class StrongNumber
  def checkStrong
     print "Enter the number: "
     input_num = gets.chomp.to_i
     num = input_num
     sum = 0 
     while num > 0 do
       rem = num % 10 
       num = num / 10 
       sum = sum + factorial(rem)
     end
     if input_num == sum
       print "#{input_num} is a strong number"
     else 
       print "#{input_num} is not a strong number"
     end 
  end
  
  private
  
  def factorial(a)
    fact = 1 
    (1..a).each do |i|
      fact = fact * i 
    end
    return fact
  end 
end

p = StrongNumber.new 
p.checkStrong

Output:

Enter the number:  145
145 is a strong number


No comments:

Post a Comment