Write a program to find prime number in minimum time complexity

Here is an example how to find prime number in optimized way. This approach is also very useful when you go for an interview.

In this approach input number from user take the square root of a number and then run loop from upto square root of the number.

*#include <iostream.h>*

*int main()*

*{*

*int num;*

*int i;*

*int count=0;*

*cout<<"Enter the number to check";*

*cin>>num;*

*double value = sqrt(num);*

*for(i=1;i<value;i++)*

*{*

*if(num%i==0)*

*{*

*count++;*

*}*

*}*

*if(count>1)*

*{*

*cout<<"number is not prime";*

*}*

*else*

*{*

*cout<<"number is prime";*

*}*

*return 0;*

*}*

## 0 comments:

## Post a Comment