⚡️ Speed up function sieve_of_eratosthenes
by 35%
#77
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 35% (0.35x) speedup for
sieve_of_eratosthenes
insrc/numpy_pandas/numerical_methods.py
⏱️ Runtime :
202 microseconds
→149 microseconds
(best of1017
runs)📝 Explanation and details
The optimized code achieves a 35% speedup through two key optimizations:
1. Eliminated repeated square root calculation
for i in range(2, int(math.sqrt(n)) + 1)
computesmath.sqrt(n)
on every loop iterationlimit = int(n ** 0.5) + 1
once and usesfor i in range(2, limit)
2. Replaced individual assignments with slice assignment
for j in range(i * i, n + 1, i): is_prime[j] = False
performs one assignment per iteration (9,407 individual assignments in profiler)is_prime[i * i : n + 1 : i] = [False] * ((n - i * i) // i + 1)
uses Python's optimized slice assignment (only 134 slice operations)Performance impact analysis:
Test case effectiveness:
The optimization particularly excels for larger inputs where the algorithmic improvements compound:
The slice assignment overhead makes it slightly slower for very small cases, but the exponential benefits for larger prime sieves make it significantly more scalable.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sieve_of_eratosthenes-mdpjedjn
and push.