5.14. Working with Prime NumbersThe 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 == 0 return true if factor > max end end end 31.prime? # true 237.prime? # false 1500450271.prime? # true |