判断是否是素数

来源:互联网 发布:勇者斗恶龙java代码 编辑:程序博客网 时间:2024/05/21 14:47

判断至i^2<=n时即可
1既不是合数也不是素数

#include <cstdlib>#include <iostream>#include <cmath>using namespace std;//判断是否是素数bool isPrimer(int n) {    if (n <= 1)        return false;    int m = floor(sqrt(n) + 0.5);    for (int i = 2; i <=m; i++) {        if (n%i==0)            return false;    }    return true;}int main() {    std::cout << "请输入要判断的数:" << std::endl;    int n;    std::cin >> n;    bool flag=isPrimer(n);    if (isPrimer(n))        std::cout << "yes" << std::endl;    else        std::cout << "no" << std::endl;    return EXIT_SUCCESS;}
原创粉丝点击