1. 程式人生 > >Problem Description——用c語言實現素數的判定

Problem Description——用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<stdio.h>
#include<math.h>
int isPrm(int x) {      //判斷素數
    if (x < 2)
        return 0;
    for (int i = 2; i <= sqrt(x); i++)
        if (x%i == 0)
            return 0;
    return 1;
}
int judge(int x, int y) {  //判斷範圍內全為素數
    for (int i = x; i <= y; i++)
        if (!isPrm(i*i+i+41))
            return 0;
    return 1;
}
int main() {
    int x, y;
    while (1) {
        scanf("%d%d", &x, &y);
        if (x == 0 && y == 0)
            break;
        if (judge(x, y))
            printf("OK\n");
        else
            printf("Sorry\n");
    }
    return 0;
}