모든 챌린지
보통 2명 해결 정답률 66.7%

List Primes With a Sieve

Find primes up to a limit by marking composite multiples.

배우게 될 내용

  • Mark composite numbers in a boolean array
  • Start crossing out at p × p
  • Collect the remaining primes

문제

번역본 보기

Return all prime numbers from 2 through limit. A prime is an integer greater than 1 divisible only by 1 and itself. Use the sieve idea: keep the next unmarked number and mark its larger multiples as composite. List results in ascending order.

Implement sieve_primes(limit).

Input

limit: The largest number that may be included.

Output

Return the primes in ascending order, or an empty list if none exist.

제약 조건

0 ≤ limit ≤ 100,000. The upper bound is inclusive. Output tests verify results, not the exact algorithm used.

예시

예시 1
입력:
limit = 12

예상 출력:
expected = [2, 3, 5, 7, 11]
입력:
long long limit = 12;

예상 출력:
std::vector<long long> expected = {2, 3, 5, 7, 11};
입력:
long limit = 12;

예상 출력:
long[] expected = new long[] {2, 3, 5, 7, 11};

설명

Mark multiples of 2 and 3 as composite. The remaining values up to 12 are 2, 3, 5, 7, and 11.

예시 2
입력:
limit = 1

예상 출력:
expected = []
입력:
long long limit = 1;

예상 출력:
std::vector<long long> expected = {};
입력:
long limit = 1;

예상 출력:
long[] expected = new long[] {};

설명

Prime numbers begin at 2, beyond this limit.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Mark composites starting from each unmarked prime candidate and continue through the limit.

힌트 2

Only numbers that stay unmarked at the end are prime.

힌트 3

Stop marking multiples once the candidate’s square exceeds the limit.

예상 복잡도

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

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 1,002 ms - 5/5 코드 보기
2 KKKaneki Ken Python 1,006 ms - 3/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 2개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.