Write Ruby program to print perfect numbers from 1 to 1000
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 printPerfectNumbers
i=1
sum=0
(1..1000).each do |n|
i = 1
sum = 0
while i < n do
sum = (sum + i) if n % i == 0
i = i + 1
end
puts n if sum == n
end
end
end
p = PerfectNumber.new
p.printPerfectNumbers
Output:
6
28
496
|
No comments:
Post a Comment