F - 求素数()

F - 求素数
Time Limit:100MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Description

 

求小于n的所有素数的数量。

Input

 

多组输入,输入整数n(n<1000000),以0结束。

Output

 

输出n以内所有素数的个数。

Sample Input

10
0

Sample Output

4
这种传统的方法Time Limit Exceeded
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int zhi(int m)
{  int k;
    int i;
    k=sqrt(m);
    for(i=2;i<=k;i++)
    {
        if(m%i==0)
            return 0;
    }
    return 1;
}
int main()
{
    int n,i,y=0;
    while(scanf("%d",&n)&&n)
    {
       for(i=2;i<=n;i++)
       {
           if(zhi(i))
            y++;
       }
       printf("%d\n",y);
    }
    return 0;

}
更新版(素数)其实这是另一种方法(厄拉多塞筛算法
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool a[1000000];
int main()
{
    int n,i,j,y;
    while(~scanf("%d",&n)&&n)
    {
        y=0;

        memset(a,1,sizeof(a));
        for(i=2; i<n; i++)
        {
            if(a[i])
            {

                y++;

                for(j=1; j*i<=n; j++)
                  {

                   a[j*i]=0;
                  }
            }

        }

        printf("%d\n",y);
    }
    return 0;


}
下面的空间和时间都会变大,但也能过
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int a[1000006];
int main()
{
    int n,i,j,y;
  for(i=0;i<=1000000;i++)
   {

    a[i]=1;
   }
  for(i=2;i<=1000000;i++)
  {
      if(a[i]==1)
      {
          for(j=2;j*i<=1000000;j++)
           {

            a[i*j]=0;
           }
      }
  }
  while(~scanf("%d",&n)&&n)
  {  y=0;

      for(i=2;i<=n;i++)
      {
          if(a[i]==1)
            {y++;}
      }
      printf("%d\n",y);
  }
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值