'commit'
This commit is contained in:
24
GESP/Level5/Eratosthenes/2.cpp
Normal file
24
GESP/Level5/Eratosthenes/2.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user