版权声明:本博全为博主学习日常,均为原创,请勿转载 https://blog.csdn.net/weixin_44332298/article/details/87904534
时间限制:1s 内存限制:32MB
题目描述
给定一个数n,要求判断其是否为素数(0,1,负数都是非素数)。
输入
测试数据有多组,每组输入一个数n。
输出
对于每组输入,若是素数就输出yes,否则输出no。
样例输入
13
样例输出
yes
题目分析
1、若n存在相异于1与其本身的因数且该因数大于sqrt(n),则必存在小于或等于sqrt(n)的因数,所以我们只需测试到sqrt(n)为止。
2、将sqrt(n)+1的值赋给变量bound,然后令i与bound作比较,这样保证了sqrt运算只进行一次。sqrt是周所周知的几个比较耗时的函数之一,该策略同样适用于strlen函数。
3、puts函数是在头文件stdio.h中,输出时最后直接带换行。改用cout,刚开始忘加括号,中间的三目运算符因为运算符优先级输出的是true为1,false为0,而不是输出“yes”和“no”。
<< 优先级比 ?: 高,先执行cout << judge(x),而后在执行三目运算符,此时的执行结果并不会输出。
cout << judge(x) ? "yes" : "no" ;
cout << endl;
加了括号就是输出yes和no了
cout << (judge(x) ? "yes" : "no") << endl;
代码
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
bool judge(int x){
if(x <= 1)
return false;
int bound = (int)sqrt(x) + 1; //为防止double值带来的精度缺失,所以采用根号值取整后再加一
for(int i = 2; i < bound; i++){
if(x % i == 0)
return false;
}
return true;
}
int main(){
int x;
while(cin >> x){
//puts(judge(x) ? "yes" : "no");
cout << (judge(x) ? "yes" : "no") << endl;
}
return 0;
}