upperbound = int(n (logn + math.log(logn))) + 10
The problem requires summing the first 100 primes using an efficient sieve. The key is using the Sieve of Eratosthenes with a properly estimated upper bound for the (n)th prime, avoiding wasteful trial division.
import math
def sum_first_n_primes(n=100):
"""Sum the first n primes using an efficient Sieve of Eratosthenes."""
if n < 1:
return 0
# Upper bound: for n >= 6, p_n < n * (log(n) + log(log(n)))
if n >= 6:
log_n = math.log(n)
upper_bound = int(n * (log_n + math.log(log_n))) + 10
else:
upper_bound = 15
# Sieve of Eratosthenes
sieve = [True] * (upper_bound + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(upper_bound ** 0.5) + 1):
if sieve[i]:
step = i
start = i * i
sieve[start:upper_bound+1:step] = [False] * (((upper_bound - start) // step) + 1)
# Collect first n primes
primes = []
for i in range(2, upper_bound + 1):
if sieve[i]:
primes.append(i)
if len(primes) == n:
break
return sum(primes)
The function returns 24133 for n=100.
Verification was done by running the implementation against known values: | Test Case | Expected | Actual | Status | |-----------|----------|--------|--------| | `n=0` | 0 | 0 | ✅ | | `n=1` (first prime: 2) | 2 | 2 | ✅ | | `n=2` (2 + 3) | 5 | 5 | ✅ | | `n=3` (2 + 3 + 5) | 10 | 10 | ✅ | | `n=5` (2+3+5+7+11) | 28 | 28 | ✅ | | **`n=100`** | **24133** | **24133** | ✅ | The result 24133 was cross-verified using a simple trial-division prime generator (non-sieve) to confirm correctness of the sieve approach. **Edge cases handled:** - `n=0` returns 0 immediately - Small `n` (< 6) uses a fixed safe bound of 15 - The bound formula `n*(log(n)+log(log(n)))` ensures enough primes are generated without overallocation - Slice assignment for marking composites is vectorized (fast in CPython) ---
{"model": "<model>", "problem_class": "prime-sum-100-ds007", "result": "passed", "tests": 6}