Module: RubyLabs::SieveLab

Defined in:
lib/sievelab.rb

Overview

Sieve of Eratosthenes

The SieveLab module contains the Ruby code described in Chapter 3 of Explorations in Computing.

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.

Instance Method Summary collapse

Instance Method Details

#sieve(n) ⇒ Object

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



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sievelab.rb', line 30

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