How many primes
Time Limit:1000MS Memory Limit:65536K
Total Submit:396 Accepted:15
Description
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 5 is prime because 1 and 5 are its only positive integer factors, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6.
Prime looks so lonely because it only has a few factors. That is the reason Junko show special preference to the prime. Now, She wants to know how many primes in [l, r].
Input
Input contains multiple test cases.
Each test case contains two integers l, r. (1 <= l <= r <= 1,000,000)
Output
For each test case, Print a line, the numbers of prime in [l, r].
Sample Input
1 1
1 10
233 666
Sample Output
0
4
71
题意:求给定区间的质数数。
题解:先将1000000以内的质数筛一遍,然后用一个数组table记录质数个数。table[i]表示1-i的素数个数,那么当询问l-r区间的质数个数时,直接输出table[r]-table[l-1]即可。
//************************************************************************// //*Author : Handsome How *// //************************************************************************// //#pragma comment(linker, "/STA CK:1024000000,1024000000") #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> //---------------------------------------------------------- const int maxn = 1000005; int table[maxn]; bool p[maxn]; void init(){ for(int i=0;i<maxn;i++)p[i]=true; p[0]=p[1]=false; for(int i=2;i<=1000000;i++){ if(p[i]){ for(int j = 2*i;j<=1000000;j+=i)p[j]=false; } } table[0]=table[1]=0; table[2]=1; for(int i=2;i<=1000000;i++)if(p[i])table[i]=table[i-1]+1; else table[i]=table[i-1]; } int main() { init(); int l ,r; while(scanf("%d %d",&l,&r)!=EOF){ printf("%d\n",table[r]-table[l-1]); } return 0; }