Class: Multipri::Prime

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/multipri/prime.rb

Instance Method Summary collapse

Constructor Details

#initialize(size = 10) ⇒ Prime

Returns a new instance of Prime.



5
6
7
# File 'lib/multipri/prime.rb', line 5

def initialize(size=10)
  @size = size
end

Instance Method Details

#eachObject



9
10
11
12
13
14
15
16
17
# File 'lib/multipri/prime.rb', line 9

def each
  return enum_for(:each) unless block_given?
  # Taken from https://rosettacode.org/wiki/Sieve_of_Eratosthenes
  nums = [nil, nil, *2..@size]
  (2..Math.sqrt(@size)).each do |i|
    (i**2..@size).step(i){|m| nums[m] = nil}  if nums[i]
  end
  nums.compact.each { |n| yield n }
end