-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
improved prime number generator to check only up to sqrt(n) instead of n #1984
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
This is cool! Can we rename the current function slow_primes() and then name the new one primes() and then we can land this pull request. Then I will create a benchmark (or you can if you want) to demonstrate how much of an improvement this is. Thanks! |
|
Ok, I've added the previous code in a separate function called slow_primes(). You'll notice that the code between the two is very similar; the only difference is that the search has been restricted in the faster method. Is this what you were looking for? |
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.
Looks good to me but the performance gain is not impressive.
@TheSuperNoob How exactly are you testing them? Could you update the benchmark to better represent the performance gain? |
…f n (TheAlgorithms#1984) * improved prime number generator to check only up to sqrt(n) instead of n * added old version as slow_primes() and named new, faster version primes() * fixed docstring in slow_primes * Add a timeit benchmark * Update prime_numbers.py Co-authored-by: Christian Clauss <[email protected]>
Describe your change:
The old algorithm checked to see if a number, n, was divisible by any number 2 - (n-1), but by pigeon hole principle it's only necessary to check up to sqrt(n). I changed the algorithm so it wouldn't do unnecessary checks.
Checklist:
Fixes: #{$ISSUE_NO}
.