문제
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.
제약 조건
0 ≤ limit ≤ 2,000,000. Return the sum using a signed 64-bit integer.
예시
입력:
limit = 12
예상 출력:
expected = 28
입력:
long long limit = 12;
예상 출력:
long long expected = 28;
입력:
long limit = 12;
예상 출력:
long expected = 28;
설명
The primes below 12 are 2, 3, 5, 7, and 11; their sum is 28.
입력:
limit = 2
예상 출력:
expected = 0
입력:
long long limit = 2;
예상 출력:
long long expected = 0;
입력:
long limit = 2;
예상 출력:
long expected = 0;
설명
There are no primes strictly below 2.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
The main cost is finding primes efficiently; naive divisibility checks for every number will be too slow.
힌트 2
Use a sieve-like approach to mark composites, then add the numbers that remain unmarked and below the limit.
힌트 3
Remember that the limit itself is excluded, even when it is prime, and small limits may contribute nothing.
예상 복잡도
O(limit log log limit) time, O(limit) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.