L1-028. 判断素数

本题的目标很简单,就是判断一个给定的正整数是否素数。

输入格式:

输入在第一行给出一个正整数N(<=10),随后N行,每行给出一个小于231的需要判断的正整数。

输出格式:

对每个需要判断的正整数,如果它是素数,则在一行中输出“Yes”,否则输出“No”。

输入样例:

2
11
111

输出样例:

Yes
No

 

 

 

 

 

 

直接判断一下 大于2 小于等于sqrt(n) 的数,能不能被n整除

当输入的是1的时候,也要输出No,因为1也不是质数

 

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

bool judge(int n){
    int len;
    len=sqrt(n);
    for(int i=2;i<=len;i++)
        if(n%i==0)
        return false;
    return true;
}

int main(){
    int n;
    int len;
    int t;
    len=sqrt(n);
    cin>>t;
    while(t--){
            cin>>n;
    if(n==1){cout<<"No"<<endl;continue;}
        if(judge(n)==false)
            cout<<"No"<<endl;
        else
            cout<<"Yes"<<endl;
    }
    return 0;

}

 

posted on 2017-03-09 12:26  猪是的念来过倒  阅读(173)  评论(0编辑  收藏  举报