1. 程式人生 > >HDU2012 素數判定

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;

}

}