(HDU2012 C++)素数判定

素数判定

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 170571 Accepted Submission(s): 60460

Problem Description

对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x

Input

输入数据有多组,每组占一行,由两个整数x,y组成,当x=0,y=0时,表示输入结束,该行不做处理。

Output

对于每个给定范围内的取值,如果表达式的值都为素数,则输出”OK”,否则请输出“Sorry”,每组输出占一行。

Sample Input

0 1
0 0

Sample Output

OK


解题思路:用一个变量记录不是素数的个数;最后做判断,若做记录的变量为0,输出OK不为0输出Sorry

源代码

#include<iostream>
using namespace std;
int main()
{
    int x, y;
    while (cin >> x >> y && (x != 0||y!=0))
    {
        int number = 0;
        for (int i = x; i <= y; i++)
        {
            int a = i*i + i + 41;
            for (int j = 2; j < a / 2; j++)
            {
                if (a%j == 0)
                {
                    number++;
                    break;
                }

            }
        }
        if (number == 0)
            cout << "OK" << endl;
        else
            cout << "Sorry" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38780240/article/details/81461563