Last active
December 20, 2015 00:59
-
-
Save elreimundo/6046192 to your computer and use it in GitHub Desktop.
Here's a pretty simple prime number generator I used for a problem in ProjectEuler (specifically, calculate the sum of every prime below 2,000,000, although this can be generalized to sum every prime below any integer)
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
def sumofprimesbelow number | |
prime_array = [3,5] | |
current_num = 7 | |
while current_num < number | |
prime_array.each do |factor| | |
if current_num % factor == 0 | |
break | |
elsif factor > Math.sqrt(current_num) | |
prime_array << current_num | |
break | |
end | |
end | |
current_num % 10 == 3 ? current_num += 4 : current_num +=2 | |
end | |
prime_array.reduce(:+) + 2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision 2 is much better as it cuts an entire array out of the process. Not sure if it's still as efficient as it could be, but it works MUCH faster than Revision 1 for large numbers.