两种 eratosthenes 筛法的时间比较,第二种快很多会比较好用

来源:互联网 发布:epub转mobi mac 编辑:程序博客网 时间:2024/04/28 19:31
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;


const int maxn = 10000005;
int vis[maxn];
int n;
//int eratosthenes()
//{
//    memset(vis,0,sizeof(vis));
//    for(int i=2;i<=n;i++)
//    {
//        for(int j=i*2;j<=n;j+=i)
//            vis[j]=1;
//    }
//}
int eratosthenes()///当算到10000000时快大概4秒的时间。此方法大概一秒能算出所有素数。
{
    memset(vis,0,sizeof(vis));
    for(int i=2;i<=(int)(sqrt(n)+0.5);i++)
    {
        if(!vis[i])
        for(int j=i*i;j<=n;j+=i)
            vis[j]=1;
    }
}


int main()
{
    scanf("%d",&n);
    eratosthenes();
    int cnt=0;
    for(int i=2;i<=n;i++)
    {
        if(!vis[i])
        {
            cnt++;
//            printf("%d ",i);
        }
    }
    printf("\nthe number :%d\n",cnt);
    return 0;
}
0 0
原创粉丝点击