Sum of Primes from 1 to n

Last Updated : 14 Sep, 2026

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

Examples:

Input: n = 5
Output: 10
Explanation: 2, 3 and 5 are prime numbers between 1 and 5(inclusive), and their sum is 2 + 3 + 5 = 10.

Input: n = 10
Output: 17
Explanation: 2, 3, 5 and 7 are prime numbers between 1 and 10(inclusive), and their sum is 2 + 3 + 5 + 7 = 17.

Try It Yourself
redirect icon

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

The idea is to check every number from 2 to n and find if it is prime by trying all possible divisors up to i / 2. If no divisor divides the number completely, it is prime, so we add it to the sum.

  • Initialize sum = 0.
  • Traverse every number i from 2 to n.
  • Assume i is prime and check all divisors from 2 to i / 2.
  • If any divisor divides i, mark it as non-prime.
  • If i is still prime, add it to sum.
  • Return the calculated sum.
C++
#include <bits/stdc++.h>
using namespace std;

int primeSum(int n)
{
    int sum = 0;

    // Check every number from 2 to n
    for (int i = 2; i <= n; i++)
    {
        bool isPrime = true;

        // Check all possible divisors up to i / 2
        for (int j = 2; j <= i / 2; j++)
        {
            if (i % j == 0)
            {
                isPrime = false;
                break;
            }
        }

        // Add the number if it is prime
        if (isPrime)
            sum += i;
    }

    return sum;
}

int main()
{
    int n = 10;
    int result = primeSum(n);

    cout << result << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static int primeSum(int n)
    {
        int sum = 0;

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++) {
            boolean isPrime = true;

            // Check all possible divisors up to i / 2
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }

            // Add the number if it is prime
            if (isPrime)
                sum += i;
        }

        return sum;
    }

    public static void main(String[] args)
    {
        int n = 10;
        int result = primeSum(n);

        System.out.println(result);
    }
}
Python
def primeSum(n):
    sum = 0

    # Check every number from 2 to n
    for i in range(2, n + 1):
        isPrime = True

        # Check all possible divisors up to i / 2
        for j in range(2, i // 2 + 1):
            if i % j == 0:
                isPrime = False
                break

        # Add the number if it is prime
        if isPrime:
            sum += i

    return sum


# Driver Code
if __name__ == "__main__":
    n = 10
    result = primeSum(n)

    print(result)
C#
using System;

class GFG {
    static int primeSum(int n)
    {
        int sum = 0;

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++) {
            bool isPrime = true;

            // Check all possible divisors up to i / 2
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }

            // Add the number if it is prime
            if (isPrime)
                sum += i;
        }

        return sum;
    }

    public static void Main()
    {
        int n = 10;
        int result = primeSum(n);

        Console.WriteLine(result);
    }
}
JavaScript
function primeSum(n)
{
    let sum = 0;

    // Check every number from 2 to n
    for (let i = 2; i <= n; i++) {
        let isPrime = true;

        // Check all possible divisors up to i / 2
        for (let j = 2; j <= Math.floor(i / 2); j++) {
            if (i % j === 0) {
                isPrime = false;
                break;
            }
        }

        // Add the number if it is prime
        if (isPrime)
            sum += i;
    }

    return sum;
}

// Driver Code
const n = 10;
const result = primeSum(n);

console.log(result);

Output
17

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

For each number, we try dividing it by possible divisors only up to its square root, because if a number has a factor larger than its square root, the corresponding smaller factor must already exist.

If no divisor is found, the number is prime, so we add it to the sum.

  • Initialize sum = 0.
  • Traverse every number i from 2 to n.
  • Assume i is prime and check divisibility from 2 to sqrt(i).
  • If any divisor is found, mark i as composite.
  • If i is still prime, add it to sum.
  • Return the final sum.
C++
#include <bits/stdc++.h>
using namespace std;

int primeSum(int n)
{
    int sum = 0;

    // Check every number from 2 to n
    for (int i = 2; i <= n; i++)
    {
        bool isPrime = true;

        // Check divisors only up to sqrt(i)
        for (int j = 2; j * j <= i; j++)
        {
            if (i % j == 0)
            {
                isPrime = false;
                break;
            }
        }

        // Add the number if it is prime
        if (isPrime)
            sum += i;
    }

    return sum;
}

int main()
{
    int n = 10;
    int result = primeSum(n);

    cout << result << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static int primeSum(int n)
    {
        int sum = 0;

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++) {
            boolean isPrime = true;

            // Check divisors only up to sqrt(i)
            for (int j = 2; j * j <= i; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }

            // Add the number if it is prime
            if (isPrime)
                sum += i;
        }

        return sum;
    }

    public static void main(String[] args)
    {
        int n = 10;
        int result = primeSum(n);

        System.out.println(result);
    }
}
Python
def primeSum(n):
    sum = 0

    # Check every number from 2 to n
    for i in range(2, n + 1):
        isPrime = True

        # Check divisors only up to sqrt(i)
        j = 2
        while j * j <= i:
            if i % j == 0:
                isPrime = False
                break
            j += 1

        # Add the number if it is prime
        if isPrime:
            sum += i

    return sum


# Driver Code
if __name__ == "__main__":
    n = 10
    result = primeSum(n)

    print(result)
C#
using System;

class GFG {
    static int primeSum(int n)
    {
        int sum = 0;

        // Check every number from 2 to n
        for (int i = 2; i <= n; i++) {
            bool isPrime = true;

            // Check divisors only up to sqrt(i)
            for (int j = 2; j * j <= i; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }

            // Add the number if it is prime
            if (isPrime)
                sum += i;
        }

        return sum;
    }

    public static void Main()
    {
        int n = 10;
        int result = primeSum(n);

        Console.WriteLine(result);
    }
}
JavaScript
function primeSum(n)
{
    let sum = 0;

    // Check every number from 2 to n
    for (let i = 2; i <= n; i++) {
        let isPrime = true;

        // Check divisors only up to sqrt(i)
        for (let j = 2; j * j <= i; j++) {
            if (i % j === 0) {
                isPrime = false;
                break;
            }
        }

        // Add the number if it is prime
        if (isPrime)
            sum += i;
    }

    return sum;
}

// Driver Code
const n = 10;
const result = primeSum(n);

console.log(result);

Output
17

[Expected Approach] Sieve of Eratosthenes - O(n * loglog(n)) Time and O(n) Space

The idea is to find all prime numbers up to n efficiently using the Sieve of Eratosthenes. We initially consider every number from 2 to n as prime, then mark the multiples of each prime as non-prime. Finally, we traverse the remaining prime numbers and add them to the sum.

  • Create a boolean array vis of size n + 1 and mark all numbers as prime.
  • Mark 0 and 1 as non-prime.
  • For every i from 2 to sqrt(n), if i is prime, mark all its multiples starting from i * i as non-prime.
  • Traverse all numbers from 2 to n.
  • If vis[i] is true, add i to the sum.
  • Return the calculated sum.
C++
#include <bits/stdc++.h>
using namespace std;

int primeSum(int n)
{
    vector<bool> vis(n + 1, true);
    int sum = 0;

    // 0 and 1 are not prime numbers
    if (n >= 0)
        vis[0] = false;
    if (n >= 1)
        vis[1] = false;

    // Find all prime numbers using Sieve of Eratosthenes
    for (int i = 2; i * i <= n; i++)
    {
        if (vis[i])
        {
            // Mark all multiples of i as non-prime
            for (int j = i * i; j <= n; j += i)
            {
                vis[j] = false;
            }
        }
    }

    // Calculate the sum of prime numbers
    for (int i = 2; i <= n; i++)
    {
        if (vis[i])
            sum += i;
    }

    return sum;
}

int main()
{
    int n = 10;
    int result = primeSum(n);

    cout << result << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static int primeSum(int n)
    {
        boolean[] vis = new boolean[n + 1];
        Arrays.fill(vis, true);

        int sum = 0;

        // 0 and 1 are not prime numbers
        if (n >= 0)
            vis[0] = false;
        if (n >= 1)
            vis[1] = false;

        // Find all prime numbers using Sieve of
        // Eratosthenes
        for (int i = 2; i * i <= n; i++) {
            if (vis[i]) {
                
                // Mark all multiples of i as non-prime
                for (int j = i * i; j <= n; j += i) {
                    vis[j] = false;
                }
            }
        }

        // Calculate the sum of prime numbers
        for (int i = 2; i <= n; i++) {
            if (vis[i])
                sum += i;
        }

        return sum;
    }

    public static void main(String[] args)
    {
        int n = 10;
        int result = primeSum(n);

        System.out.println(result);
    }
}
Python
def primeSum(n):
    vis = [True] * (n + 1)
    sum = 0

    # 0 and 1 are not prime numbers
    if n >= 0:
        vis[0] = False
    if n >= 1:
        vis[1] = False

    # Find all prime numbers using Sieve of Eratosthenes
    i = 2
    while i * i <= n:
        if vis[i]:

            # Mark all multiples of i as non-prime
            for j in range(i * i, n + 1, i):
                vis[j] = False

        i += 1

    # Calculate the sum of prime numbers
    for i in range(2, n + 1):
        if vis[i]:
            sum += i

    return sum


# Driver Code
if __name__ == "__main__":
    n = 10
    result = primeSum(n)

    print(result)
C#
using System;

class GFG {
    static int primeSum(int n)
    {
        bool[] vis = new bool[n + 1];

        for (int i = 0; i <= n; i++)
            vis[i] = true;

        int sum = 0;

        // 0 and 1 are not prime numbers
        if (n >= 0)
            vis[0] = false;
        if (n >= 1)
            vis[1] = false;

        // Find all prime numbers using Sieve of
        // Eratosthenes
        for (int i = 2; i * i <= n; i++) {
            if (vis[i]) {
                
                // Mark all multiples of i as non-prime
                for (int j = i * i; j <= n; j += i) {
                    vis[j] = false;
                }
            }
        }

        // Calculate the sum of prime numbers
        for (int i = 2; i <= n; i++) {
            if (vis[i])
                sum += i;
        }

        return sum;
    }

    public static void Main()
    {
        int n = 10;
        int result = primeSum(n);

        Console.WriteLine(result);
    }
}
JavaScript
function primeSum(n)
{
    let vis = new Array(n + 1).fill(true);
    let sum = 0;

    // 0 and 1 are not prime numbers
    if (n >= 0)
        vis[0] = false;
    if (n >= 1)
        vis[1] = false;

    // Find all prime numbers using Sieve of Eratosthenes
    for (let i = 2; i * i <= n; i++) {
        if (vis[i]) {

            // Mark all multiples of i as non-prime
            for (let j = i * i; j <= n; j += i) {
                vis[j] = false;
            }
        }
    }

    // Calculate the sum of prime numbers
    for (let i = 2; i <= n; i++) {
        if (vis[i])
            sum += i;
    }

    return sum;
}

// Driver Code
const n = 10;
const result = primeSum(n);

console.log(result);

Output
17
Comment