C Program to Check Whether a Number is Prime or not?


A prime number is a number that is divisible only by two numbers itself and one. The factor of a number is a number that can divide it.

The list of the first ten prime numbers is 2, 3, 5, 7, 11, 13, 17, 23, 29, 31.

A number that is not prime is a composite number. A composite number is a number that can be divided by more than two numbers.

Else then prime and composite there is 1 which is neither Prime nor composite because it can be divided only by itself.

How to check if a number is prime or composite to check if a number is prime there are two conditions that should be checked

1) It should be a whole number greater than 1.

2) it should have only two factors i.e., one and the number itself.

If these two conditions are satisfied, then we can say a number is a prime number.

In our program, we will check dividing the number by each number smaller than that number. If any number smaller than the given number divides it then it is not Prime number. Otherwise, it is a prime number.

Example

Let's take an example of two numbers and check whether they are prime or not using this process.

Input − Number1 − 42
Output − 42 is not a prime number

Logic

We will divide 42 by every number greater than 1 and smaller than 42. So,

42/2 = 21 i.e. 42 is divisible by 2, this means 42 is not a prime number because it is divisible by another number.

Input − Number2 − 7
Output − 7 is a prime number

Logic Explanation

We will divide seven by every number greater than 1 and smaller than 7. So,

7 is not divisible by 2, so the code will check for the next number i.e. 3

7 is not divisible by 3, so the code will check for the next number i.e. 4

7 is not divisible by 4, so the code will check for the next number i.e. 5

7 is not divisible by 5, so the code will check for the next number i.e. 6

7 is not divisible by 6, This means that 7 is divisible by only 1 and 7 this means 7 is a prime number.

look at the above logic what does the number would be 1000 plus or 100000 Plus then the program would take that many iterations for the for a loop this method would take a lot of computation time. So to reduce the number of iterations they must be a better way.

An optimised solution to this is run the for loop only halfway. this means if the number is 77 the loop will run only till 38. This will reduce the number of iterations required so we will use this algorithm to create our program.

Example

#include <stdio.h>
int main() {
   int num = 33, flag = 0;
   for(int i=2 ; i < num/2 ; i++) {
      if(num%i == 0) {
         printf("%d is not a prime number", num);
         flag = 1;
         break;
      }
   }
   if(flag == 0) {
      printf("%d is a prime number", num);
   }
}

Output

33 is a prime number

Updated on: 07-Nov-2023

34K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements