Problema
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.
Vincoli
0 ≤ limit ≤ 2,000,000. Return the sum using a signed 64-bit integer.
Esempi
Input:
limit = 12
Output atteso:
expected = 28
Input:
long long limit = 12;
Output atteso:
long long expected = 28;
Input:
long limit = 12;
Output atteso:
long expected = 28;
Spiegazione
The primes below 12 are 2, 3, 5, 7, and 11; their sum is 28.
Input:
limit = 2
Output atteso:
expected = 0
Input:
long long limit = 2;
Output atteso:
long long expected = 0;
Input:
long limit = 2;
Output atteso:
long expected = 0;
Spiegazione
There are no primes strictly below 2.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
The main cost is finding primes efficiently; naive divisibility checks for every number will be too slow.
Suggerimento 2
Use a sieve-like approach to mark composites, then add the numbers that remain unmarked and below the limit.
Suggerimento 3
Remember that the limit itself is excluded, even when it is prime, and small limits may contribute nothing.
Complessità attesa
O(limit log log limit) time, O(limit) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.