首页 > 其他 > 详细

洛谷 P3912 素数个数

时间:2018-01-07 13:39:33      阅读:328      评论:0      收藏:0      [点我收藏+]

题目描述

1,2,\cdots,N1,2,?,N 中素数的个数。

输入输出格式

输入格式:

 

1 个整数NN。

 

输出格式:

 

1 个整数,表示素数的个数。

 

输入输出样例

输入样例#1: 复制
10
输出样例#1: 复制
4

说明

• 对于40% 的数据,1 \le N \le 10^61N106;

• 对于80% 的数据,1 \le N \le 10^71N107;

• 对于100% 的数据,1 \le N \le 10^81N108。

思路:RE,线性筛一边就可以做出来。bool只占一个字节,所以不会MLE。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,tot;
int prime[1000000];
bool yes[10000000];
void shai(){
    memset(yes,true,sizeof(yes));
    yes[1]=false;
    for(int i=2;i<=n;i++){
        if(yes[i])    prime[++tot]=i;
        for(int j=1;i*prime[j]<=n;j++){
            yes[i*prime[j]]=false;
            if(i%prime[j]==0)    break;    
        }
    }
}
int main(){
    scanf("%d",&n);
    shai();
    cout<<tot;
}

把上面的代码多开一个0 就可以AC了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,tot;
int prime[1000000];
bool yes[10000000];
void shai(){
    memset(yes,true,sizeof(yes));
    yes[1]=false;
    for(int i=2;i<=n;i++){
        if(yes[i])    prime[++tot]=i;
        for(int j=1;i*prime[j]<=n;j++){
            yes[i*prime[j]]=false;
            if(i%prime[j]==0)    break;    
        }
    }
}
int main(){
    scanf("%d",&n);
    shai();
    cout<<tot;
}

当然听说大佬用了一种叫Meissel Lehmer Algorithm的算法跑的飕飕的。对于我一个蒟蒻来说,这个算法太高级了,诸君还是自行学习吧。我在这里就不粘代码了。

洛谷 P3912 素数个数

原文:https://www.cnblogs.com/cangT-Tlan/p/8227520.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!