Find out if the number is a prime number or not

Background:
  1. Prime number should not be divisible by 2. If n%2 is 0 then it is not a prime number.
  2. Moreover, a prime number is only divisible by itself and 1. Hence to find out a prime number we will iterate through a loop from 2 to n-1.
  3. At any point if n%i is 0 then it is not a prime number. If we reach end of loop and if the number is not divisible by anything till n then it is a prime number.
  4. The reason why we are starting the loop at 2 is because 2 is also a prime number. 

Implementation:
 
bool isPrime(int n)
{
 int count = 0;
 bool flag = false;
 
 if( n ==2 ) {
  count = 0;
 }
  
 for(int i=2;i < n;i++)
 {
  if(((n % i) == 0) && (n!=i))
  {
   print("Not Prime");
   break;
  }
  else
   count = 0;
 }
  if(count == 0)
  {
   print("Prime");
   flag = true;
  }  
 return flag;
}


Complexity:
O(n)

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...