HDU2012素數判定
阿新 • • 發佈:2019-01-28
素數判定
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 103031 Accepted Submission(s): 36053
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 直接給出AC的程式碼,上面有註釋;
#include<iostream> #include<cstdio> #include<cstring> using namespace std; bool isprime(int n) //判斷n是否為素數;若為素數返回true 否則返回 flase; { int i; if (n <= 1)return false; for (i = 2; i*i <= n; i++) { if (n%i == 0)return false; } return true; } int main() { int x, y, s; while (cin >> x >> y) { if (x == 0 && y == 0)break; int flag = 1; for (int i = x; i <= y; i++) { s = i*i + i + 41; if (!isprime(s))flag = 0; //若x,y範圍內有 s=n^2+n+41不是素數的則 標記為0,表示該區間的數不全為素數; } if (flag)cout << "OK" << endl; //特別注意輸出的時候“OK”是全部字母都大寫的,“Sorry”是隻有首字母大寫的; else cout << "Sorry" << endl; //一般遇到這種輸出的話直接從題目上覆制粘連過來就好了; } }