How to determine prime numbers in the C programming language?

The common method of determining whether a number is a prime number is trial division. This involves dividing the number n by all integers from 2 to the square root of n. If n is evenly divisible by any of these numbers, then it is not a prime number; if n is not divisible by any of them, then it is a prime number.

The specific implementation is as follows:

#include <stdio.h>
#include <math.h>

// 判断一个数是否为素数
int isPrime(int n) {
    if (n <= 1) {
        return 0;
    }
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return 0;
        }
    }
    return 1;
}

int main() {
    int n;
    printf("请输入一个数:");
    scanf("%d", &n);
    if (isPrime(n)) {
        printf("%d是素数\n", n);
    } else {
        printf("%d不是素数\n", n);
    }
    return 0;
}

After running the program, input a number, and the program will determine if the number is a prime number and output the result.

bannerAds