Prime number is a natural number (integer) greater than 1 that doesn’t have any positive divisor other than 1 and itself.
Here is the program to check whether a number is prime or not.
#include <stdio.h> int CheckPrime(int n) { int i = 0; for(i=2; i<=n/2; ++i) { if(n%i == 0) { return 0; } } return 1; } int main() { int n, i, ret=0; printf("Enter a positive integer: "); scanf("%d",&n); ret = CheckPrime(n); if (ret == 1) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n); return 0; }
Here the function, CheckPrime(), checks whether the input argument is prime or not. If the argument is prime, then the function returns 1, otherwise, 0. The function divides the input argument with each number from 2 to half of the number. If the argument is divisible by any number, the function returns 0, i.e. the number is not prime. When the loop ends, that means the passed argument is not divisible by any number, the function returns 1. We don’t need to check with a number greater than half of the argument because a number can not have proper divisor greater than the half of a number.