Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Last active December 20, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elreimundo/6046192 to your computer and use it in GitHub Desktop.
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)
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
@elreimundo
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment