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;
}
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;
}
相关文章推荐
- poj 3978 primes
- POJ 3978 Primes(求范围素数个数)
- poj 3978 Primes
- POJ 3978(求素数)
- POJ 3978(求素数)
- POJ 3978(求素数)
- POJ 3978 Primes(求范围素数个数)
- POJ 3978 Primes 已被翻译 可能会
- POJ 3978 Primes(素数筛选法)
- POJ 3978
- poj 1159 Palindrome
- POJ 3468 A Simple Problem with Integers
- poj 1470 最近公共祖先
- POJ 2187 Beauty Contest(凸包+旋转卡壳)
- POJ 2891 Strange Way to Express Integers ★ (扩展欧几里德解同余式组)
- poj 1250 Tanning Salon
- POJ 1062 昂贵的聘礼
- poj - 1470 - Closest Common Ancestors
- OpenJudge/Poj 1159 Palindrome
- poj 1328 -- Radar Installation