中級 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つずつ開いてみましょう。

ヒント 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 Н"Никита "Programmer" Python 1,002 ms - 5/5 コードを見る
2 KKKaneki Ken Python 1,006 ms - 3/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が2件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。