素数判断

题目很简单,输入一个数字判断它是不是素数。

最简单的就是这个数字除以所有大于2小于其本身的数,但我们可以考虑,如果一个数有a,b两个数字相乘得来,那么一个数一定大于等于sqrt(x),一个数小于等于sqrt(x),所以只需要计算到sqrt(x)即可。

#include <iostream>
#include<cstdio>
#include<math.h>
using namespace std;

bool judge(int x){
     if(x <= 1)
        return false;
     int bound = (int)sqrt(x)+1;//计算枚举上界
     for(int i=2;i<bound;i++){
        if(x%i == 0)
            return false;
     }
     return true;
}
int main()
{
    int x;
    scanf("%d",&x);
    puts(judge(x) ? "yes" : "no");//这种方式输出很方便啊有木有
    return 0;
}

 

posted @ 2018-03-15 09:36  Shaw_喆宇  阅读(133)  评论(0编辑  收藏  举报