Prime number in c


#include<stdio.h>
#include<math.h>
int main()
{
 int num,i,flag=0;
  printf("Enter the number:\n");
  scanf("%d",&num);
   for(i=2;i<=sqrt(num);i++)
    { 
        if(num%i==0)
         {
             flag=1;
             break;
         }
     
    }     
  
        if(num==1)
         printf("Neither prime nor composite number");
         else if(flag==1)
         printf("Not a Prime number");
         else
         printf("prime number");
         
         return 0;
    
}

 

Explanation:

 

 The program is to find whether the given number is prime or not.

observe the above program,

The integer variable 'num' is taken as input. The integer variable flag is set to zero. 

In the For loop statement 'i' is set as 2, the condition applied i <=sqrt(num) is an inbuilt function to find the square root of a number. This function comes under #include<math.h> header file. whenever we use this function, we have to include the header file at the top of the program. 

Why did we use the sqrt() function?

 sqrt function will find the square root of the given number.

example: Suppose, we accepted num is 24

                The square root of 24 is 4, taking as an integer value.

               Take two factors of 24, whose product is 24. The two numbers can be 4*6==24

               Suppose 6>sqrt(24) then 4<=sqrt(24), if this was wrong, then 4*6 would not be equal to 24, implying that 4*6 were not proper factorization of 24.

All we need is to find the smaller factor of a number. The smaller factor of a number is always less than equal to the square root of that number. If it is not equal, then the number is a prime number. Hence the condition is applied i <=sqrt(num).

Inside the for loop, if-condition is applied, if the number is divided by 'i' then, the number is not a prime number. The flag will become 1, and the break statement will take control outside the for-loop.

1 is neither prime nor composite number. Hence, an if-condition for 1 has applied if the condition becomes false, the control will move to else-if-condition if the flag is 1 then, the number is not prime, else a number is a prime number.

               

  Algorithm:

  step 1: start

  step 2: accept num;

  step 3: i=2;

  step 4: flag=0;

  step 5: Is i<=sqrt(num) then

               DO

              If num% i==0 then

               flag=1;

               break;

               End If

                i=i+1;

               Done

  step 6:  IF num==1

              PRINT Neither prime nor composite

            ELSE IF flag==1

            PRINT Not a prime number

            Else 

            PRINT Prime number

         ENDIF


Flowchart:

 

c-program-find-whether-number-prime-not