Условие
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.
Примеры
Ввод:
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.
Ввод:
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
Помечайте составные числа, начиная с каждого непомеченного кандидата в простые, и идите до limit.
Подсказка 2
Только числа, которые в конце остались непомеченными, являются простыми.
Подсказка 3
Прекращайте помечать кратные, как только квадрат кандидата превышает limit.
Ожидаемая сложность
время O(n log log n), доп. память O(n)
Ссылки
Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.