质数筛选
最终算法模板,比赛就写这个!!
int prime[100010];
void Prime(){
for (int i = 2; i <= 1000000; i++) {
prime[i] = true;
}
for (int i = 1; i * i <= 1000000; i++) {
if (prime[i]) {
for (int j = i * i; j <= 1000000; j += i) {
prime[j] = false;
}
}
}
}
或者写下面这个:线性筛
#define SIZE 1000000
int main()
{
int check[SIZE] = {0};//元素值为0代表是素数
int prime[SIZE] = {0};
int pos=0;
int flag;
for (int i = 2 ; i < SIZE ; i++)
{
if (!check[i])//如果是素数
prime[pos++] = i;
for (int j = 0 ; j < pos && i*prime[j] < SIZE ; j++)
{
check[i*prime[j]] = 1;//筛掉
//标注一
if (i % prime[j] == 0)
break;
}
}
printf("%.2f", (double)clock()/CLOCKS_PER_SEC);
return 0;
}
下面是具体解释,可以不看,比赛套上面模板即可!!!
![](https://img2018.cnblogs.com/blog/1454456/201811/1454456-20181119214228044-1809688019.png)
###如何判断一个数是不是质数?简单方法一:
![](https://img2018.cnblogs.com/blog/1454456/201811/1454456-20181119215344441-1163614886.png)
int is_prime(int n) {
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return 0; // 不是质数
}
}
return 1; // 是质数
}
##素数筛选算法:
![](https://img2018.cnblogs.com/blog/1454456/201811/1454456-20181119220344796-975079526.png)
####算法一:时间复杂度---- O(nlogn)
![](https://img2018.cnblogs.com/blog/1454456/201811/1454456-20181119220352279-1219400795.png)
for (int i = 2; i <= n; ++i) {
is_prime[i] = 1;
}
for (int i = 2; i <= n; ++i) {
for (int j = i * 2; j <= n; j += i) {
is_prime[j] = 0;
}
}
####算法二优化:
![](https://img2018.cnblogs.com/blog/1454456/201811/1454456-20181119220423117-1867892215.png)
for (int i = 2; i <= n; ++i) {
is_prime[i] = 1;
}
for (int i = 2; i * i <= n; ++i) {
if (is_prime[i]) {
for (int j = i * i; j <= n; j +=i) {
is_prime[j] = 0;
}
}
}