To solve this problem, we need to compute the sum of all prime numbers up to a given number ( n ). A prime number is a number greater than 1 that has no divrs other than 1 and itself. The most efficient way to find all primes up to ( n ) is using the Sieve of Eratosthenes algorithm, which allows us to mark non-prime numbers in linear time relative to ( n ).
Approach
The Sieve of Eratosthenes works as follows:
- Initialize: Create a boolean array (or list) of size ( n+1 ) where each element is set to
True(indicating the number is initially considered prime), except indices 0 and 1 which are set toFalse(since they are not primes). - Mark Non-Primes: For each number ( i ) starting from 2 up to the square root of ( n ):
- If ( i ) is still marked as prime (i.e.,
sieve[i]isTrue), mark all multiples of ( i ) starting from ( i^2 ) as non-prime (set toFalse). This is because smaller multiples of ( i ) would already have been marked by smaller primes.
- If ( i ) is still marked as prime (i.e.,
- Sum Primes: Sum all indices in the sieve array that are still marked as
True(these are the primes).
Solution Code
def sum_of_primes(n):
if n < 2:
return 0
# Initialize sieve: sieve[i] is True if i is prime
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
# Mark non-primes
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
# Mark multiples of i starting from i*i
sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i])
# Sum all primes
return sum(i for i, is_prime in enumerate(sieve) if is_prime)
Explanation
- Edge Case Handling: If ( n ) is less than 2, the sum of primes is 0 since there are no primes below 2.
- Sieve Initialization: The sieve list is initialized to
Truefor all numbers from 0 to ( n ), except 0 and 1 which are non-prime. - Marking Non-Primes: For each prime ( i ), we mark all multiples of ( i ) starting from ( i^2 ) as non-prime. This is efficient because we skip smaller multiples that have already been marked by previous primes.
- Summing Primes: We iterate over the sieve list and sum all indices where the value is
True(primes).
This approach has a time complexity of ( O(n \log \log n) ), which is optimal for finding primes up to ( n ). It is much faster than checking each number individually for primality, especially for large values of ( n ).
Example: For ( n = 10 ), the primes are 2,3,5,7, so the sum is ( 2+3+5+7 =17 ). The function returns 17 as expected. For ( n=2 ), it returns 2, and for ( n=1 ), it returns 0.
This solution efficiently computes the sum of primes up to any given ( n ) using the Sieve of Eratosthenes algorithm.


作者声明:本文包含人工智能生成内容。