Most Optimized Program for Prime Number - Programmer's Mind




           Program for Prime Number is the most commonly asked program in interviews. We can develop the same program in many ways. Logic of the program may differ from person to person. But the most important thing to consider, in order to draw the attention of the interviewer is optimization of the code. Here is the Program for Prime Number which is Most Optimized.If any one of us find more optimized program for prime number than this then share that in comments so that the code will be useful to all of us.

To Know Basic Concept of Prime Number (Click Here)

Most Optimized Program for Prime Number:



Output:













Explanation:

           In this program we are decreasing the number of iterations by running the loop from i to n/i. 
'1' is a common factor to any number so why to check the condition for 1.So lets start the loop from 2 

For Instance,
Let us consider number 25
Here 25 is not divisible by 2 so there is no possibility to have factors in the range (n/2 to n-1)
i.e..,in (12 - 24).By applying this logic on every iteration we can decrease the loop size.

If the number is divisible by any 'i' value in the loop means that it is divisible by a number which is neither 1 nor that number.So it is not a prime number .Print that the number is  not a prime and return the control so that the remaining iterations can be skipped.


Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment