HDU2012 素数判定

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 65536/32768 K (Java/Others)

Description
对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x<y<=50),判定该表达式的值是否都为素数。
Input
输入数据有多组,每组占一行,由两个整数x,y组成,当x=0,y=0时,表示输入结束,该行不做处理。
Output
对于每个给定范围内的取值,如果表达式的值都为素数,则输出"OK",否则请输出“Sorry”,每组输出占一行。
Sample Input

0 1
0 0

Sample Output

OK

Hint
JGShining
Source
  C语言程序设计练习(二)  
Related problem
2015 2010 2016 2005 2019

在下偏向于写个判断是否为素数的bool函数,主函数再进行调用,if true 则继续,else直接跳出,“sorry”.

代码如下:

#include <iostream>
using namespace std;
bool isPrime(int a)
{
if(a<=1)
return false;
if(a==2||a==3||a==5||a==7)
return true;
for(int i=2;i*i<=a;i++)
    if(a%i==0)
        return false;
return true;
}
int main()
{
int x,y,count=0;
while(cin>>x>>y,x!= 0 && y != 0)
{
int n=x;
for(;n<=y;n++){
    if(!isPrime(n*n+n+41){
        cout<<"Sorry"<<endl;
        break;
        }
    count++;
}
if(count==y-x+1)
    cout<<"OK"<<endl;

}

}

猜你喜欢

转载自blog.csdn.net/qq_41627235/article/details/82791844