October 2006
Intermediate to advanced
888 pages
16h 55m
English
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 ...
Read now
Unlock full access