Prime Number with out Prime Class



a = [1,4,5,12,9,5,3,5]

class Array
  def prime_numbers
    self.select(&:prime?)
  end
end

class Integer
  def prime?
    return if self <= 1
    (2..Math.sqrt(self).ceil).none? { |i| (self % i).zero? }
  end
end

 a.prime_numbers
=> [5, 5, 3, 5]

Comments

Post a Comment

Popular posts from this blog

Rails Kaminari - Ajax pagination

Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value: '\xF0\x9F\x8C\x9D')