Last active
December 21, 2015 23:09
-
-
Save dustinbrownman/6380589 to your computer and use it in GitHub Desktop.
Returns all the primes between 2 (the first prime) and a given number using the 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
| def sieve(number) | |
| if number < 2 | |
| raise TypeError.new("Must be a number greater than 2") | |
| end | |
| primes =* (2..number) | |
| primes.each do |prime| | |
| primes.reject! do |number| | |
| prime != number && number % prime == 0 | |
| end | |
| end | |
| end |
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
| require 'rspec' | |
| require 'sieve' | |
| describe 'prime_sift' do | |
| it 'returns the prime number 2 for a range of 2' do | |
| sieve(2).should eq [2] | |
| end | |
| it 'returns the prime numbers 2 and 3 for a range of 3' do | |
| sieve(3).should eq [2, 3] | |
| end | |
| it 'does not return non-primes' do | |
| sieve(4).should eq [2, 3] | |
| sieve(100).should eq [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] | |
| end | |
| it 'raises an exception if given a number less than 2' do | |
| expect { sieve(1) }.to raise_exception | |
| end | |
| it 'raises an exception if given something other than a number' do | |
| expect { sieve("two") }.to raise_exception | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment