class PrimePrinter::PrimeGenerator

Public Class Methods

new() click to toggle source
# File lib/prime_printer/prime_generator.rb, line 2
def initialize
  @generator = Fiber.new do
    Fiber.yield 2
    value = 3
    loop do
      Fiber.yield value if is_prime? value
      value += 2
    end
  end
end

Public Instance Methods

next(count = 1) click to toggle source
# File lib/prime_printer/prime_generator.rb, line 13
def next(count = 1)
  if count == 1
    @generator.resume
  else
    [].tap do |primes|
      count.times { primes.push @generator.resume }
    end
  end
end

Private Instance Methods

is_prime?(n) click to toggle source
# File lib/prime_printer/prime_generator.rb, line 25
def is_prime?(n)
  Math.sqrt(n).floor.downto(2).each {|i| return false if n % i == 0}
  true
end