2到n之间的所有素数:
算法1:
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= sqrt(num); i++)
if (num % i == 0) return false;
return true;
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
for (int num = 2; num <= n; num++)
if (isPrime(num))
cout << num << " ";
return 0;
}
算法2:
#include <iostream>
#include <vector>
using namespace std;
void sieveOfEratosthenes(int n) {
// 初始化bool数组,所有元素默认为true
vector<bool> prime(n+1, true);
for (int p = 2; p*p <= n; p++) {
// 如果prime[p]没有被改变,那么它一定是一个素数
if (prime[p] == true) {
// 更新所有p的倍数为非素数
for (int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
// 输出所有素数
for (int p = 2; p <= n; p++)
if (prime[p])
cout << p << " ";
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
cout << "Following are the prime numbers smaller than or equal to " << n << endl;
sieveOfEratosthenes(n);
return 0;
}
算法2简短版本:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
vector<bool> prime(n+1, true);
for (int p = 2; p*p <= n; p++) {
if (prime[p]) {
for (int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
for (int p = 2; p <= n; p++)
if (prime[p]) cout << p << " ";
return 0;
}
稍微不一样的算法2:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cin >> n;
bool* prime = new bool[n+1];
memset(prime, true, n+1);
for (int p = 2; p*p <= n; p++)
if (prime[p])
for (int i = p*p; i <= n; i += p)
prime[i] = false;
for (int p = 2; p <= n; p++)
if (prime[p]) cout << p << " ";
delete[] prime;
return 0;
}