- Prime number should not be divisible by 2. If n%2 is 0 then it is not a prime number.
- 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.
- 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.
- 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