mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
fix: rewrite prime numbers using linear sieve (#1810)
* fix: rewrite prime numbers using linear sieve * fix code scanning error * clang-format and clang-tidy fixes for0afd463b
* fix sign-compare warning * clang-format and clang-tidy fixes for6ddff0f7
Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
parent
4e3abd4601
commit
1f6c39bcf2
@ -9,14 +9,22 @@
|
||||
/** Generate an increasingly large number of primes
|
||||
* and store in a list
|
||||
*/
|
||||
std::vector<int> primes(int max) {
|
||||
max++;
|
||||
std::vector<int> primes(size_t max) {
|
||||
std::vector<int> res;
|
||||
std::vector<bool> numbers(max, false);
|
||||
for (int i = 2; i < max; i++) {
|
||||
if (!numbers[i]) {
|
||||
for (int j = i; j < max; j += i) numbers[j] = true;
|
||||
res.push_back(i);
|
||||
std::vector<bool> is_not_prime(max + 1, false);
|
||||
for (size_t i = 2; i <= max; i++) {
|
||||
if (!is_not_prime[i]) {
|
||||
res.emplace_back(i);
|
||||
}
|
||||
for (int p : res) {
|
||||
size_t k = i * p;
|
||||
if (k > max) {
|
||||
break;
|
||||
}
|
||||
is_not_prime[k] = true;
|
||||
if (i % p == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
@ -25,9 +33,9 @@ std::vector<int> primes(int max) {
|
||||
/** main function */
|
||||
int main() {
|
||||
std::cout << "Calculate primes up to:\n>> ";
|
||||
int n;
|
||||
int n = 0;
|
||||
std::cin >> n;
|
||||
std::vector<int> ans = primes(n);
|
||||
for (int i = 0; i < ans.size(); i++) std::cout << ans[i] << ' ';
|
||||
for (int p : ans) std::cout << p << ' ';
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user