Prime Number(求n内质数的个数)
Description
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Input
Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.
The number of datasets is less than or equal to 30.
Output
For each dataset, prints the number of prime numbers.
Sample Input
10 3 11
Output for the Sample Input
4 2 5
解题思路:题意很简单,求n内质数的个数,注意n最大也就1e6,既可用埃氏筛也可以用欧拉筛模板,水过!
AC代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e6+5; 4 int n,cnt=0,prime[maxn];bool isp[maxn]; 5 void euler_sieve(){ 6 memset(isp,true,sizeof(isp)); 7 isp[0]=isp[1]=false; 8 for(int i=2;i<maxn;++i){ 9 if(isp[i])prime[cnt++]=i; 10 for(int j=0;j<cnt&&i*prime[j]<maxn;++j){ 11 isp[i*prime[j]]=false; 12 if(i%prime[j]==0)break; 13 } 14 } 15 } 16 int main(){ 17 euler_sieve(); 18 while(~scanf("%d",&n)){ 19 int num=0; 20 for(int i=0;prime[i]<=n&&i<cnt;++i)num++; 21 printf("%d\n",num); 22 } 23 return 0; 24 }