Sha256: 514bbf69231c766491f3324ab6daee6bd8185447353782d562eeabce5b875393

Contents?: true

Size: 897 Bytes

Versions: 11

Compression:

Stored size: 897 Bytes

Contents

module RubyLabs
  
=begin rdoc
  
== Sieve of Eratosthenes

The SieveLab module contains the Ruby code described in Chapter 3
of <em>Explorations in Computing</em>.

The module has only one method, +sieve+, which uses the Sieve of Eratosthenes
to generate a list of prime number up to a specified maximum value.
The method is an introduction to iteration, using iterators
to make and filter lists of numbers.

=end
  
module SieveLab

# Create a list of all prime numbers between 2 and +n+.
#
# Example:
#   >> sieve(1000)
#   => [2, 3, 5, 7, ... 983, 991, 997]
#
# :call-seq:
#   sieve(n) => Array
#
#-- 
# :begin :sieve 
  def sieve(n)
    worksheet = Array(2..n)
    primes = []

    while worksheet.first < sqrt(n)
      primes << worksheet.first
      worksheet.delete_if { |x| x % primes.last == 0 }
    end

    return primes + worksheet
  end
# :end :sieve

end # SieveLab

end # RubyLabs

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
rubylabs-1.0.2 lib/sievelab.rb
rubylabs-1.0.1 lib/sievelab.rb
rubylabs-1.0.0 lib/sievelab.rb
rubylabs-0.9.8 lib/sievelab.rb
rubylabs-0.9.7 lib/sievelab.rb
rubylabs-0.9.6 lib/sievelab.rb
rubylabs-0.9.5 lib/sievelab.rb
rubylabs-0.9.4 lib/sievelab.rb
rubylabs-0.9.3 lib/sievelab.rb
rubylabs-0.9.2 lib/sievelab.rb
rubylabs-0.9.1 lib/sievelab.rb