How to find prime numbers in the C programming language?

One common method to determine if a number is prime is to use the trial division method, which involves checking if the number can be evenly divided by integers between 2 and its square root. If it cannot, then the number is prime.

Here is an example of code written in C language for checking prime numbers:

#include <stdio.h>

// 判断是否为素数
int isPrime(int num) {
    // 小于等于1的数不是素数
    if (num <= 1) {
        return 0;
    }

    // 判断是否能被2到其平方根之间的整数整除
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return 0;
        }
    }

    return 1;
}

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

    return 0;
}

In this code, the isPrime function is used to determine if a number is a prime number. A return value of 1 indicates it is a prime number, while a return value of 0 indicates it is not. The main function uses the scanf function to receive user input, then uses the isPrime function to determine if it is a prime number, and finally outputs the result.

bannerAds