九度OJ題目1047:素數判定
阿新 • • 發佈:2019-02-01
時間限制:1 秒
記憶體限制:32 兆
特殊判題:否
- 題目描述:
-
給定一個數n,要求判斷其是否為素數(0,1,負數都是非素數)。
- 輸入:
-
測試資料有多組,每組輸入一個數n。
- 輸出:
-
對於每組輸入,若是素數則輸出yes,否則輸入no。
- 樣例輸入:
-
13
- 樣例輸出:
-
yes
#include <stdio.h> #include <stdbool.h> //使用了布林型別需新增該標頭檔案 #include <math.h> //使用了求平方根函式sqrt需新增該標頭檔案 bool judge(int x){ //對每個數依次測試大於1但不大於其平方根的數字能否整除它 if(x<=1) return false; int bound=(int)sqrt(x)+1;//計算列舉上界,根號值取整後再加1是為防止double值帶來的精度損失 for(int i=2;i<bound;i++){ if(x%i==0) return false; } return true; } int main(){ int n; while(scanf("%d",&n) != EOF){ puts(judge(n)?"yes":"no");//依據函式返回值輸出答案 } return 0; } /************************************************************** Problem: 1047 User: zpy Language: C++ Result: Accepted Time:0 ms Memory:1032 kb ****************************************************************/