题目描述:
Problem 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
思路:
素数的判定,是要求掌握的最基本的算法,方法有很多,直接背诵自己最喜欢并且复杂度相对较低的一种。
实现(C++):
#include <iostream>
#include <math.h>
using namespace std;
int isPrime(int n){ //判断n是否为素数
if(n==0) return 0;
if(n==2||n==3) return 1;
for(int i=2; i<=sqrt(n); i++)
if(!(n%i)) return 0;
return 1;
}
int main(){
int x, y;
while(cin>>x>>y){
if(x==0&&y==0)
break;
int flag=1;
for(int i=x; i<=y; i++)
if(!isPrime(i*i+i+41)){
flag=0;
break;
}
if(flag)
cout<<"OK"<<endl;
else
cout<<"Sorry"<<endl;
}
}