当前位置:   article > 正文

C++判断一个数是不是质数_c++判断质数

c++判断质数

详见及参考:
https://www.nowcoder.com/practice/b8bb5e7703da4a83ac7754c0f3d45a82?tpId=225&tags=&title=&difficulty=0&judgeStatus=0&rp=0

质数只能被1及其本身整除的正整数。例如2是质数:2÷1=2,2÷2=1,即2被1整除是2,2被其本身整除是1。2只能被1及其本身整除,因此它是质数。

判断一个数n是不是质数,

  • 1.首先,任何正整数都能被1及其本身n整除,因此将循环范围定在2n-1之间。
  • 2.再进一步思考,如果 n n n能被一个大于 n \sqrt{n} n 的数整除,
    我们不妨设这个大于 n \sqrt{n} n 的数为 t t t,则 n n n也一定能被 n / t n/t n/t整除,而 n / t n/t n/t是小于 n \sqrt{n} n 的,所以只需验证输入的数字 n n n能否被 2 2 2 n \sqrt{n} n 之间的任何数整除。
    举个例子:
    例如 n = 21 n=21 n=21, 21 21 21能被一个大于 21 \sqrt{21} 21 7 7 7 49 \sqrt{49} 49 整除( 21 ÷ 7 = 3 21÷7=3 21÷7=3),则反过来 21 21 21也能被小于 21 \sqrt{21} 21 的3即 9 \sqrt{9} 9 整除。
    因此我们只需要验证输入的数字 21 21 21能否被 2 2 2到$\sqrt{21} $之间的任何数整除即可。
#include <iostream>
using namespace std;

bool isPrime(int x){
    for(int i=2; i*i<=x; i++){
        if (x % i == 0)
            return false;
    }
    return true;
}


int main() {

    int num;
    cin >> num;
    
    if (isPrime(num)){
        cout << "是质数" <<endl;
    }
    else
        cout << "不是质数" <<endl;

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
#include <iostream>
using namespace std;

int main() {

    int num;
    cin >> num;

    bool flag = true; // 必须先初始化flag。若直接bool flag;会报错。
    for (int i=2; i*i<=num; i++){ //遍历到根号num就可以了
        if (num % i == 0) { //可以整除,说明num不是质数
            flag = false;
            break;
        }
    }

    if (flag)
        cout << "是质数" <<endl;
    else
        cout << "不是质数" <<endl;

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/75360
推荐阅读
相关标签
  

闽ICP备14008679号