facebook like button

31 March, 2011

program 24: prime number more efficient program

The need:
     In the program 17 to find whether a number is prime or not I told you that I'll be giving you more efficient program do find that after you know certain things. Now you know those things. So here is the program.

The code: 
--------------------------------------------

#include<stdio.h>
#include<math.h>
main()
{
    int i,j,k=0,n;
    double m;
    printf("Enter the number...");
    scanf("%d",&i);    // scanning i as integer
    if(i<2)
    {
    printf("Prime numbers start from 2\n");
    }
    else if(i==2)
    {
    printf("Number is prime\n");
    }
    else
    {
m=sqrt(i);         //m is square root of i
    n=ceil(m);         //ceil function
    for(j=2;j<=n;j++)
    {
         if(i%j==0)
         {
         k++;
         break;
         }
    }
         if(k>=1)
         printf("The number is not a prime number.\n\n");
        else
        printf("The number is a prime number.\n\n");
}
}

-----------------------------------------

The approach:
   A number will be prime if it can not be fully divided by any number except itself and 1. The program finds this by dividing given number by a range of numbers and checking whether it has been fully divided or not. In program 17 that range was taken to be 2 to 'i/2' where 'i' is the number to be checked. But now suppose a number 'x' has factors then we can always make couples of factors. In those couples one will be greater than the square root of 'x' and the other will be less. You cannot find a number both of whose factors are greater than its square root. This implies that to check whether a number 'i' is prime or not I have to check only up to its square root. To be on safe side I am checking up to the smallest integer greater than or equal the square root of 'i'. The ceil() function takes care of this. So 'm' is the smallest integer greater than or equal the square root of 'i'. One new statement used here is break. This is used when we want to break the flow of loop like here when we have find a factor of that number, we need not check further so its better to break loop. To know more about break see program30.


Remark:
    If the number to be checked is greater than 4, the value of 'm' will be less than 'i/2'so number of runs of loop will be less. That's the meaning of 'more efficient' here.
    Ex.  Suppose I have to check whether 10000 is a prime number or not, then program 17 will run loop 10000/2=5000 times while this program will run the loop for sqrt(10000)=100 times.
Therefore you see that number of runs of loop have been reduced.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply