Last active
January 4, 2016 18:08
-
-
Save AndrewGuard/8658155 to your computer and use it in GitHub Desktop.
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
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. | |
# Find the sum of all the primes below two million. | |
# Slow | |
def is_prime?(num) | |
(2..Math.sqrt(num)).each { |i| | |
if num % i == 0 && i < num | |
return false | |
end | |
} | |
true | |
end | |
def find_primes(num) | |
primes = [] | |
num.times do |i| | |
if is_prime?(i) | |
primes << i | |
end | |
end | |
primes | |
end | |
def sum_of_primes(num) | |
primes = find_primes(num) | |
sum = primes.reduce(:+) | |
sum = sum - 1 | |
end | |
p sum_of_primes(2_000_000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment