How can we determine if a number is prime in C++?

To determine if a number is a prime number, you can use the following method:

#include <iostream>
#include <cmath>

bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }

    int sqrt_num = sqrt(num);
    for (int i = 2; i <= sqrt_num; i++) {
        if (num % i == 0) {
            return false;
        }
    }

    return true;
}

int main() {
    int num;
    std::cout << "请输入一个整数:";
    std::cin >> num;

    if (isPrime(num)) {
        std::cout << num << "是素数" << std::endl;
    } else {
        std::cout << num << "不是素数" << std::endl;
    }

    return 0;
}

In the code above, we have defined a function called isPrime that takes an integer as input and returns a boolean value indicating whether the integer is a prime number. The function uses a loop that starts from 2 and goes up to the square root of the number to check for factors. If a factor is found that divides the number, then the number is not a prime.

In the main function, we obtain an integer from user input, then we call the isPrime function to determine if the number is a prime number, and output the result.

广告
Closing in 10 seconds
bannerAds