Showing posts with label Ruby program to check perfect number. Show all posts
Showing posts with label Ruby program to check perfect number. Show all posts

Ruby program to check perfect number



Write a Ruby program to check perfect number

Perfect Number:  a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.

class PerfectNumber
  def checkPerfectNumber
    i=1
    sum=0
    puts "Enter the number"
    n = gets.chomp.to_i
    while i < n do 
      sum = (sum + i) if n % i == 0
      i = i + 1
    end
    if sum == n
      puts "Given number is perfect number"
    else
      puts "Given number is not a perfect number"
    end
  end
end

p = PerfectNumber.new 
p.checkPerfectNumber


Output:


Enter the number
 6
Given number is perfect number
=> ni