Skip to content

Instantly share code, notes, and snippets.

@AndrewGuard
Last active January 4, 2016 18:08
Show Gist options
  • Save AndrewGuard/8658155 to your computer and use it in GitHub Desktop.
Save AndrewGuard/8658155 to your computer and use it in GitHub Desktop.
# 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