杭电2012--------素数判定C++版

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

#include<iostream>
using namespace std;
void f(int x,int y)
{
    int n,s,c=0,i;
    for(n=x;n<=y;n++)
    {
        s=n*n+n+41;
        for(i=2;i<s;i++)
            if(s%i==0)break; 
         if(s==i)
         c++;
    }
    if(c==y-x+1)
    cout<<"OK"<<endl;
    else cout<<"Sorry"<<endl;
}
int main()
{
    int x,y;
    while(cin>>x>>y)
    {
        if(x==0&&y==0)break;
        f(x,y);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43289087/article/details/88623410