/*
Primes
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2975 Accepted: 1144
Description
A pretty straight forward task, calculate the number of primes between 2 integers.
Given 2 integers A ¡Ü B < 105 what¡¯s the number of primes in range from A to B inclusive.
Note: A prime number is a positive integer greater than 1 and is divisible by 1 and itself only. For N to be prime it is enough to test the divisibility
of numbers less than or equal to square root of N.
Input
As many as 1000 lines, each line contains 2 integers A and B separated by a space. Input is terminated when A = B = -1 (Do not process this line).
Output
For every line in input ¨C except for the last line where A = B = -1 - print the number of prime numbers between A and B inclusive.
Sample Input
0 9999
1 5
-1 -1
Sample Output
1229
3
Source
Seventh ACM Egyptian National Programming Contest
*/
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
bool notprime[100005] = {0};
void primejudge()
{
notprime[0] = 1;
notprime[1] = 1;
for(int i = 2; i <= 100000; ++i)
{
if(notprime[i]) continue;
for(int j = 2; j <= sqrt(float(i)); ++j)
{
if(i % j == 0)
{
notprime[i] = 1;
}
}
for(int k = 2; k * i <= 100000; ++k)
{
notprime[i*k] = 1;
}
}
}
int prime_count(int x, int y)
{
int s = 0;
for(int i = x; i <= y; ++i)
{
if(!notprime[i]) ++s;
}
return s;
}
int main()
{
primejudge();
int a = 0, b = 0;
while(true)
{
scanf("%d%d", &a, &b);
if(a == -1 && b == -1) break;
if(a < 1) a = 1;
if(b < 1) b = 1;
printf("%d\n", prime_count(a, b));
}
return 0;
}
转载于:https://my.oschina.net/locusxt/blog/145878