-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Improve sieve of eratosthenes and remove duplicate #5043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
# Do even numbers separately | ||
primes = [2] | ||
for i in range(4, num + 1, 2): | ||
sieve[i] = False |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we don't want to optimize it like this to keep its original algorithm. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is the same algorithm, but since 2 is the only even prime, you can check it seperately and remove unnecessary tests
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd suggest stick to Wiki.
p = 3 | ||
while p * p <= num: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use range
here.
>>> prime_sieve_eratosthenes(10) | ||
2,3,5,7, | ||
>>> prime_sieve_eratosthenes(20) | ||
2,3,5,7,11,13,17,19, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Move these tests to the existing file.
|
||
return prime | ||
return primes | ||
|
||
|
||
if __name__ == "__main__": |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if __name__ == "__main__": | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Describe your change:
I removed a duplicate of sieve of eratosthenes in favour of the older one, and improved the older one by iterating by 2 elements each time and removing the math dependency
Checklist:
Fixes: #{$ISSUE_NO}
.