VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-find-sum-prime-numbers-1-n/

⇱ Program for sum of primes from 1 to n - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for sum of primes from 1 to n

Last Updated : 20 Mar, 2025

Given a positive integer n, compute and return the sum of all prime numbers between 1 and n (inclusive).

Examples:

Input : 10
Output : 17
Explanation : Primes between 1 to 10 : 2, 3, 5, 7.

Input : 11
Output : 28
Explanation : Primes between 1 to 11 : 2, 3, 5, 7, 11.

[Naive Approach] Trial Division Method - O(n^2) time and O(1) space

This method checks each number from 2 to n for primality by dividing it by all numbers from 2 to i/2. If any divisor is found, the flag is set to 0, indicating the number is not prime. If no divisors are found, the number is added to the sum. After completing the loop, the sum of all primes up to n is returned.


Output
17

[Better Approach] Square Root Method - O(n*sqrt(n)) time and O(1) space

To optimize the above method, we check whether a number is prime by iterating only up to the square root of the number. This approach checks each number from 2 to n for primality by testing divisibility up to its square root. If a number is prime (i.e., it has no divisors other than 1 and itself), it is added to the sum. Finally, the sum of all prime numbers up to n is returned.


Output
17

[Expected Approach] Using Sieve of Eratosthenes - O(nloglogn) time and O(n) space

The idea is to use Sieve of Eratosthenes to efficiently check which numbers are prime in the range from 1 to n.

This process marks all prime numbers up to n by iterating through the numbers and marking their multiples as non-prime. After completing the marking, it sums up all the numbers that remain marked as prime.


Output
17


Comment