#include <iostream>
#include <vector>
using namespace std;
void sieveOfEratosthenes(int n) {
vector<bool> isPrime(n+1, true);
for (int p = 2; p*p <= n; p++) {
if (isPrime[p]) {
for (int i = p*p; i <= n; i += p) {
isPrime[i] = false;
}
}
}
for (int p = 2; p <= n; p++) {
if (isPrime[p]) {
cout << p << " ";
}
}
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Prime numbers up to " << n << " are: ";
sieveOfEratosthenes(n);
return 0;
}
此代碼實現了素數篩選法,輸出小于等于給定數n的所有素數。