Files
algorithms/src/numbers/find_primes.hpp
2025-10-28 14:57:10 +03:00

32 lines
830 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <vector>
// находит все простые числа от 0 до n
// Решето Эратосфена
namespace alg
{
inline std::vector<int> find_primes(int n)
{
std::vector<int> r;
std::vector<bool> is_prime(n + 1, true);
// 0 и 1 не являются простыми числами
is_prime[0] = is_prime[1] = false;
// Исключаем все чётные числа, кроме 2
for (int i = 4; i <= n; i += 2) is_prime[i] = false;
// Перебираем только нечётные числа, начиная с 3
for (int p = 3; p * p <= n; p += 2)
if (is_prime[p])
for (int i = p * p; i <= n; i += 2 * p) is_prime[i] = false;
for (int p = 3; p <= n; p += 2)
if (is_prime[p]) r.push_back(p);
return r;
}
}