Created
October 13, 2016 02:11
-
-
Save jm-maniego/4621bce5447bfa66be11213d79a4176c to your computer and use it in GitHub Desktop.
Collect primes using Sieve of Eratosthenes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PrimalityChecker | |
module EratosthenesSieve | |
def self.prime?(n) | |
# Start at 7, because the obvious ones are crossed out | |
!(7..Math.sqrt(n)).any? {|p| n % p == 0 } | |
end | |
end | |
end | |
class PrimeCollector | |
include Enumerable | |
def prime?(n, primality_checker = PrimalityChecker::EratostheneseSieve) | |
return true if [1,2,3,5].include?(n) | |
return false if [3,5].any?{|p| n % p == 0} | |
return false if n.even? # This line is useless, because of .step(@limit, 2) in #each | |
primality_checker.prime?(n) | |
end | |
def initialize(limit = 1000) | |
@limit = limit | |
end | |
def each(&block) | |
[2, *3.step(@limit, 2)].select(&method(:prime?)).each(&block) | |
end | |
end | |
prime_collector = PrimeCollector.new(1000) | |
primes = prime_collector.map{|p| p};0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment