Last active
December 15, 2015 22:19
-
-
Save TravisL12/5332269 to your computer and use it in GitHub Desktop.
Calculate the sum of prime numbers below a maximum number of integers (max_prime). This is in response to the Project Euler Problem 10: http://projecteuler.net/problem=10 This problem states to find the sum of all prime numbers less than 2,000,000.
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
| max_prime = 51 | |
| array = Array.new(max_prime) { |i| i } | |
| not_primes = [] | |
| primes = [] | |
| array.each do |i| | |
| if i > 1 && i <= (max_prime ** 0.5) | |
| 0.upto(max_prime) do |j| | |
| sieve = i**2 + (j * i) # Sieve_of_Eratosthenes algorithm to find non-primes | |
| if sieve > max_prime | |
| break | |
| elsif not not_primes.include? sieve | |
| not_primes << sieve | |
| end | |
| end | |
| end | |
| end | |
| array.each { |i| primes << i if not not_primes.include? i } | |
| primes.shift(2) | |
| puts primes.inject(:+) | |
| primes.inject(:+) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment