您的位置:首页 > 其它

POJ3978

2013-03-24 11:16 330 查看
/*
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 – 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<iostream>
using namespace std;
bool isPrime(int n)//判断是否是素数
{
if(n==1||n==0) return false;//1不是素数
if(n!=2&&n%2==0) return false;//2是素数,清除2的倍数
for(int i=3; i*i<=n; i=i+2)
{
if(n%i==0) return false;
}
return true;
}
int main()
{
int a,b;
int count;
while(cin>>a>>b)
{
count=0;
if(a==-1&&b==-1)
break;
for(int i=a; i<=b; i++)
{
if(isPrime(i)) count++;
}
cout<<count<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: