Prime for Ruby
I came across this algorithm for determining if a number is prime and I thought it might be fun to implement in Ruby. Some objectives were to stay true to the original algorithm, do it in less code and keep it just as readable. Here's my result:
1 2 3 4 5 6 7 8 9 10 11 |
class Fixnum def prime? (2..self.abs**0.5).each {|n| return false if self%n == 0} return true end end 2.prime? # => true 5.prime? # => true 12.prime? # => false 101.prime? # => true |
I figured this is something that I could add to the Fixnum class so I could just ask a number if it is prime or not (in true OO fashion). I check the range from 2 to the square root of the number. If it is divisible it isn't a prime, if not then it is.
Of course, there is a Prime class for Ruby, so in many cases this would be unnecessary.





