Back to challenges
Medium 0 solved 0% acceptance

Sum of Primes Below a Limit

Add all primes strictly below a limit.

What you'll learn

  • Find all primes below a limit with a sieve
  • Mark multiples instead of testing each number
  • Sum values efficiently

Problem

A prime is an integer greater than 1 divisible only by 1 and itself. Add every prime strictly smaller than limit. The limit itself is excluded even when it is prime.

Implement prime_sum(limit).

Input

limit: The exclusive upper bound.

Output

Return the sum of the eligible primes, or 0 when none exist.

Constraints

0 ≤ limit ≤ 2,000,000. Return the sum using a signed 64-bit integer.

Examples

Example 1
Input:
limit = 12

Expected output:
expected = 28
Input:
long long limit = 12;

Expected output:
long long expected = 28;
Input:
long limit = 12;

Expected output:
long expected = 28;

Explanation

The primes below 12 are 2, 3, 5, 7, and 11; their sum is 28.

Example 2
Input:
limit = 2

Expected output:
expected = 0
Input:
long long limit = 2;

Expected output:
long long expected = 0;
Input:
long limit = 2;

Expected output:
long expected = 0;

Explanation

There are no primes strictly below 2.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The main cost is finding primes efficiently; naive divisibility checks for every number will be too slow.

Hint 2

Use a sieve-like approach to mark composites, then add the numbers that remain unmarked and below the limit.

Hint 3

Remember that the limit itself is excluded, even when it is prime, and small limits may contribute nothing.

Expected complexity

O(limit log log limit) time, O(limit) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.