Files
python/GESP/Level5/Eratosthenes/2.cpp

24 lines
625 B
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
const int N = 210;
int b[N];
int n = 200; // 200以内的质数
int main() {
// 初始化标记数组中所有数字都是质数
memset(b, 1, sizeof b);
// 理论依据:任何非质数,都会有一个因数不会大于他的算术平方根。所以优化后代码:
for (int i = 2; i <= sqrt(n); i++) { // 优化上限n到sqrt(n)
if (b[i])
for (int j = i * 2; j <= n; j += i) // 倍数都是合数
b[j] = 0;
}
// 输出有哪些质数
for (int i = 2; i <= n; i++)
if (b[i])
cout << i << " ";
return 0;
}