Prime number program in Ruby



Write a prime number program in Ruby

Prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

class PrimeNumber
  def checkPrime
     print "Enter the number: "
     num = gets.chomp.to_i
     check = 0 
     if (num == 0) || (num == 1)
       check = 1 
     else 
       (2..(num - 1)).each do |i|
         if (num % i == 0) && (i != num)
           check = 1 
           break
         end
       end
     end
    if check == 0  
      print "#{num} is a prime number"
    else
      print "#{num} is not a prime number"
    end 
  end
end

p = PrimeNumber.new 
p.checkPrime

Output:

Enter the number:  13
13 is a prime number


No comments:

Post a Comment