zoukankan      html  css  js  c++  java
  • 洛谷 P3912 素数个数

    题目描述

    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的算法跑的飕飕的。对于我一个蒟蒻来说,这个算法太高级了,诸君还是自行学习吧。我在这里就不粘代码了。

    细雨斜风作晓寒。淡烟疏柳媚晴滩。入淮清洛渐漫漫。 雪沫乳花浮午盏,蓼茸蒿笋试春盘。人间有味是清欢。
  • 相关阅读:
    中国剩余定理
    Codeforces 240 F. TorCoder
    ZOJ 1202 Divide and Count
    洛谷 3380 【模板】二逼平衡树(树状数组套权值线段树)
    bzoj 3196/ Tyvj 1730 二逼平衡树 (线段树套平衡树)
    uva 10791
    uva 699 The Falling Leaves
    uva 839 Not so Mobile
    2017 济南综合班 Day 5
    2017 济南综合班 Day 4
  • 原文地址:https://www.cnblogs.com/cangT-Tlan/p/8227520.html
Copyright © 2011-2022 走看看