Section 5.15. Implicit and Explicit Numeric Conversion


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





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net