Sunday, February 9, 2014

Prime Number


            
The Prime Number term is actually used in mathematics.  Definition of Prime Number is "The number Which is not divisible by any number except itself and 1". For example 2,3,5,7,11,........... Generally we can find a number is prime or not in mathematics but how we can find prime numbers in C,C++,Java,............etc.Now a days in most interviews,interviewer will asking one question that is "Write a program for given number is prime or not?". Recently one of my friend attend C language interview last two days back. He shared his interview experience with me. My friend said to me which type of questions they asked to him, from that discussion i am posting one important question that is "Write a program for given number is Prime or not"?. We can solve this type question in general way but when we attempting interview we can little bit different way. 

Program to find given number is  Prime Number  or not in C Language:
This is a basic program to find given number is prime or not.


#include  <stdio.h>
#include <conio.h>

int main(void){
      int a = 0;//this variable is used to store given number
      int count = 0;//this variable is used to know how many times given number is divisible.
      println("Enter a number: ");
      scanf("%d",&a);//taking entered number to a variable
      
      for(int i = 0;i <= a;i++){
          if(a%i == 0){
               count++;
          }
      }
      if(count == 2){
          printf("Given number %d is Prime Number",a);
     }


Output :

Enter a number : 19

Given number 19 is Prime Number



In another way, we can find the given number is prime or not.In Maths one short cut formula is available.The formula is If you want to find given number is prime or not.
Step 1:
           First we find the square root of given number.
           Ex: Given number is 19 . Square Root of 19 is 4.358898.
Step 2:
           If given number is divisible by less than or equal to 4. Means number is divisible by 1 or 2 or 3 or 4.
Step 3:
           Number is not divisible by 1 or 2 or 3 or 4 numbers.So 19 is Prime Number.



Now we can write the above steps convert to C Language.

#include<stdio.h>

#include<conio.h>
#include<math.h>

int main(void){

   int inputNumber = 0;
   int count = 0;
   printf("Enter a number");
   scanf("%d", &inputNumber);
   
   int  sqrtValue = sqrt(inputNumber);
   for(int i = 2;i <= sqrtValue;i++){
        if(inputNumber%i == 0){
         count++;
        }
   }
   if(count == 1){
     printf("Given number %d is Prime Number",inputNumber);
   }else{
     printf("Given number %d is not a Prime Number",inputNumber);
   }
   return 0;
}


In above program, for loop is started from 2 value not 1 because Every number is divisible by 1.That's why for loop is start from 2.


See this related posts:

write program to sort integer number
How many ways are there to register jdbc driver
Floyd's triangle