Write a C program to check whether a number is prime or not

Description: Take a number as input. Print if it is a prime number. A prime number has only two factors, 1 and itself.

Hint:

  • Try to divide the number by 2, 3, 4 … Stop when a divisor is found, or when the divisor is more than the square root.

C program to check a prime number

#include <stdio.h>

int main(void) {
    int n, isPrime = 1;

    printf("Enter a number: ");
    scanf("%d", &n);

    if (n < 2) {
        isPrime = 0;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }

    if (isPrime) {
        printf("%d is a prime number\n", n);
    } else {
        printf("%d is not a prime number\n", n);
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: 29
29 is a prime number

How it works

  • Numbers less than 2 are not prime.
  • If n has a divisor, it has one which is not more than its square root. So the loop stops at i * i <= n.
  • break ends the loop as soon as a divisor is found.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.