Check whether a number is a prime number or not in C

05 min read

C program to check if the given number is a prime number or not is shown below. A Prime number is a whole number greater than 1 whose only factors are 1 and itself. So in order to find such a number,  we need to divide the given number by every other number less than that except 1. If the given number is perfectly divisible by any of the numbers less than that number, then it is not a prime number. This logic is used to implement this program.


#include <stdio.h> int main() { int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=1; break; } } if (flag==0) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n); return 0; }

 

Output:

Enter a positive integer: 23 23 is a prime number.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error