5.14. Working with Prime Numbers

The mathn library defines a class for generating prime numbers. The iterator each generates these in succession in an infinite loop. The succ method naturally generates the next prime number.

For example, here are two ways to list the first 100 primes:

require 'mathn'

list = []
gen = Prime.new
gen.each do |prime|
  list << prime
  break if list.size == 100
end

# or alternatively:

list = []
gen = Prime.new
100.times { list << gen.succ }

The following code tests the primality of a number. Note that for large numbers and slow machines, this may take a while:

require 'mathn' class Integer def prime? max = Math.sqrt(self).ceil max -= 1 if max % 2 == 0 pgen = Prime.new pgen.each do |factor| return false if self % factor ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.