Contact Learn C
Copy

Program 22:To know whether given number is Prime or Not

Program 22:
#include<stdio.h>
main()
{
  int num,i,count=0;
  printf("Enter a number to check whether it is prime or not\n");
  scanf("%d",&num);
  for(i=1;i<=num;i++)
  {
    if(num%i==0)
    {
      count++;
    }
  }
  if(count==2)
  {
    printf("The given number %d is Prime Number\n",num);
  }
  else
  {
    printf("The given number %d is not Prime Number\n because The number is divisible by\n",num);
    for(i=1;i<=num;i++)
    {
      if(num%i==0)
      {
        printf("%d\n",i);
      }
    }
  }
}
Explanation: The prime number should be divisible by 1 and itself.This is the main concept of this program.
  1. The program starts with initializing
    • num → To store number
    • i Temporary variable
    • count → To store number of divisors
  2. printf("Enter a number to check whether it is prime or not\n");
    scanf("%d",&num);
    To take number from user
  3. for(i=1;i<=num;i++)
    {
    if(num%i==0)
    {
    count++;
    }
    }
    Let us assume num=253. The loop will traverse from i=1 to 253 In each iteration the number num=253 is divided by i.For example
    • Iteration 1:i=1,i less than 253
      • In if num%i==0 → 253%1==0 which is true
      • Then count increments by 1.So count=1;
    • Iteration 2:i=2,i less than 253
      • In if num%i==0 → 253%2==0 which is false
      • As the condition is false the count remains same so count is still count=1
    • Iteration 3:i=3,i less than 253
      • In if num%i==0 → 253%3==0 which is false
      • As the condition is false the count remains same so count is still count=1
    • Like this it goes on till iteration 11
    • ...........
    • Iteration 11:i=11,i less than 253
      • In if num%i==0 → 253%11==0 which is true
      • Then count increments by 1.So count=2;
    • Like this for every divisor of number(253) the count will get incremented and in this case of number(253) there are 4 divisors (they are:1,11,13,153) until i=253
    • So the count=4
  4. if(count==2)
    {
    printf("The given number %d is Prime Number\n",num);
    }
    else
    {
    printf("The given number %d is not Prime Number\n 
            because The number is divisible by\n",num);
    for(i=1;i<=num;i++)
    {
    if(num%i==0)
    {
    printf("%d\n",i);
    }
    }
    }
    As for Prime number there will be only 2 divisors 1 and the number itself If the number is prime number the count will be 2(i.e. count=2) But in this case where number is 253 the count=4 so the condition will be false and prints that it is not a prime number and display its divisors using the same logic as in case of counting number of divisors except instead of using count to increment we used printf to print values of divisors
Output:

To know whether given number is Prime or Not
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide