Skip to content

Instantly share code, notes, and snippets.

@diemer
Last active October 4, 2016 05:36
Show Gist options
  • Select an option

  • Save diemer/5233bea9f84276a6e73cf16dcde185b7 to your computer and use it in GitHub Desktop.

Select an option

Save diemer/5233bea9f84276a6e73cf16dcde185b7 to your computer and use it in GitHub Desktop.
An implementation of the Sieve of Eratosthenes in Ruby
# An implementation of the Sieve of Eratosthenes in Ruby
# I recently read about it in The Imposter's Handbook(https://bigmachine.io/products/the-imposters-handbook)
# and thought it would be a fun experiment to try to code, just off the
# description and the example animation on
# Wikipedia(https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
class PrimeSieve
def initialize(max)
@numbers = (2...max).to_a
@current_prime = 2
end
def primes
while @current_prime <= @numbers.count
mark_composite(@current_prime, @numbers)
@current_prime += 1
end
@numbers
end
private
def mark_composite(cp,n)
mp = cp * 2
n.count.times do
n.delete(mp) if n.include? mp
mp += cp
end
end
end
require 'minitest/autorun'
require './prime_sieve'
class PrimeSieveTest < Minitest::Unit::TestCase
def setup
@sieve = PrimeSieve.new(200)
end
def test_first_number_is_two
assert_equal 2, @sieve.primes.first
end
def test_prime_calculation
expected_primes = "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199"
assert_equal @sieve.primes, expected_primes.split(", ").map {|i| i.to_i }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment