Created
October 19, 2015 13:55
-
-
Save TylerRockwell/6c0b07fde254930d94ac to your computer and use it in GitHub Desktop.
Find Primes
This file contains 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 'minitest/autorun' | |
require 'minitest/pride' | |
# Write a method which returns the first n primes, where n is provided to the | |
# method as a parameter. | |
# | |
# Remember that the % operator (modulo) is your friend. It returns a zero if one | |
# number is divisible by another number. In other words, 4 % 2 == 0. | |
# WRITE YOUR CODE HERE. Name your method `primes`. | |
def primes(n) | |
found_primes = [] | |
current_num = 2 | |
while found_primes.count < n | |
prime = true | |
(2...current_num).each do |divisor| | |
if current_num % divisor == 0 | |
prime = false | |
break | |
end | |
end | |
found_primes << current_num if prime | |
break if found_primes.count == n | |
current_num += 1 | |
end | |
found_primes | |
end | |
class PrimesChallenge < MiniTest::Test | |
def test_one_prime | |
assert_equal [2], primes(1) | |
end | |
def test_two_primes | |
assert_equal [2, 3], primes(2) | |
end | |
def test_ten_primes | |
assert_equal [2, 3, 5, 7, 11, 13, 17, 19, 23, 29], primes(10) | |
end | |
def test_thousand_primes | |
first_thousand = primes(1000) | |
assert first_thousand.include?(6991) | |
assert first_thousand.include?(7907) | |
refute first_thousand.include?(1000) | |
end | |
def test_no_primes | |
assert_equal [], primes(0) | |
end | |
def test_bad_input | |
assert_equal [], primes(-34) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment