Created
May 27, 2011 07:15
-
-
Save johana-star/994790 to your computer and use it in GitHub Desktop.
Euler Project Problem #010
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
# Solution to Project Euler's tenth problem | |
# http://projecteuler.net/index.php?section=problems&id=10 | |
# Find the sum of all primes below two million. | |
def generate_primes(ceiling) | |
primes, count = [1, 2], 1 | |
until primes.last > ceiling do | |
numbers = (primes[count-1]**2+1..primes[count]**2).to_a | |
1.upto(count) {|c| numbers.select! {|number| number%primes[c] != 0}} | |
primes.concat(numbers) | |
count += 1 | |
end | |
primes.shift #remove 1 | |
return primes | |
end | |
def sum_primes(primes, ceiling) | |
sum = 0 | |
primes.each do |p| | |
if p < ceiling then | |
sum = sum + p | |
else | |
return sum | |
end | |
end | |
end | |
number = 2000000 | |
primes = generate_primes(number) | |
sum = sum_primes(primes, number) | |
puts sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment