Last Updated: November 18, 2017
·
1.969K
· xurde

Ruby Integer instance to self check whether is Prime number or not

In my case, I need ruby standard Integer instances to be able to self check whether they are or not a prime number.

Taking a mathematical definition from the Wikipedia, we can conclude this:

A simple but slow method of verifying the primality of a given number n is known as trial division.
It consists of testing whether n is a multiple of any integer between 2 and \sqrt{n}.

So this is pretty easy to take into ruby code:

class Integer
  def is_prime?
    prime = true
    for r in 2..Math.sqrt(self).to_i
      if (self % r == 0)
        prime = false
        break
      end
    end
    return prime
  end
end