C Program to Check Prime Numbers

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

  1. Firstly, check if the number is less than or equal to 1; if it is, then it is not a prime number.
  2. Then starting from 2, check one by one if the number can be divided by numbers from 2 to the square root of n. If it can be divided, then it is not a prime number.
  3. If the number cannot be divided by any number between 2 and the square root of n, then it is a prime number.

Here is an example code written in the C language to determine prime numbers.

#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 num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    if (isPrime(num)) {
        printf("%d is a prime number.\n", num);
    } else {
        printf("%d is not a prime number.\n", num);
    }
    
    return 0;
}

The code first defines a function isPrime to determine if a number is prime. Then in the main function, it reads the user’s input number, calls the isPrime function to check if the number is prime, and outputs the result.

bannerAds