40026118素数的个数

本博客提供了一个算法,用于计算不超过给定整数n的素数数量。通过预处理生成素数表,然后遍历计算目标范围内素数的数量。
40026118素数的个数
 
试题描述

给定整数 n ,请你统计不超 n 的素数的个数。

输入
仅包含一个正整数 n 。
输出
不超过 n 的素数的个数。
输入示例
11
输出示例
5
其他说明
数据范围:1 <= n <= 10^6 。
样例说明:有 2、3、5、7、11 共 5 个素数。
 
 
 1 #include<iostream>
 2 #define LL long long
 3 #define maxn 1000010
 4 using namespace std;
 5 LL read()
 6 {
 7     LL x=0,f=1;
 8     char c=getchar();
 9     while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
10     while(isdigit(c)){x=x*10+c-'0';c=getchar();}
11     return x*f;
12 }
13 bool prime[maxn];
14 LL a;
15 void prime_table()
16 {
17     for(int i=2;(LL)i<=a;i++) prime[i]=1;
18     for(int i=2;(LL)i*i<=a;i++)
19         if(prime[i]) for(LL j=i*i;j<=a;j+=i) prime[j]=0;
20     return;
21 }
22 
23 int main()
24 {
25     a=read();
26     prime_table();
27     int cnt=0;
28     for(int i=2;i<=a;i++)if(prime[i]) cnt++;
29     printf("%d\n", cnt);
30     system("pause");
31     return 0;
32 }
View Code

 

转载于:https://www.cnblogs.com/wls001/p/4975192.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值