# Find whether prime or not

Hey,

what wrong in my code?

```#include "stdio.h" /* written like this because this editor is not able to show angle brackets becauz of html*/

void prime(int num);
int main() {

int num;
scanf("%d",&num);
prime(num);

return 0;
}

void prime(int num){

int i = 2;

while(i <= num-1){

if(num % i == 0){

printf("Not Prime");
break;

}
}

if(num == i)
printf("Prime");

}
```

Thanks

1. You forgot to increment i.

2. This is really inefficient. Think on how to optimize a bit more.

3. It’s kinda considered rude to ask “What is wrong with my code” and paste your code. EDIT
Now that someone else mentioned it, you just have to check until the square root of n. It would be something like

``````void prime(int num){
int i=2;
if(num%2==0) { // Special case for 2
printf("NOT PRIME");
return;
}
int n = sqrt(num);
++i;
while(i<=n){ //Check until sqrt(num)
if(num%i==0){
printf("NOT PRIME");
return;
}
i+=2; //Increase by 2 to avoid checking even numbers
}
printf("PRIME");
}``````

Put i++ in the while loop,else its an infinite loop.
And your code can be optimized a lot more ,for example you needn’t check for all i from 2 to number,instead you can check it from 2 to num/2 because ----“think yourself” and try to optimize much more like this,though your code length might increase its okay try to reduce execution time for now

while(i <= num-1){

``````    if(num % i == 0){

printf("Not Prime");
break;

}
i++;
}
``````

above code is correct you forget the increment part.

Also check for numbers of the form (6k±1), because other than 2 and 3, all primes are of the form (6k±1).

Thus write the code as:

``````bool isPrime(int n)
{
if(n<2)
return false;
else if(n<=3)
return true;
if(n%2==0 || n%3==0)
return false;
for(int i=5;i<=sqrt(n);i+=6)
{
if(n%i==0 || n%(i+2)==0)
return false;
}
return true;
}
``````

This will be more efficient.

int n;
int status=0;
Console.Writeline(“Enter the number”);
for(int i=2;i<n/2;i++)
{if(n%i==0)
{
Console.Writline(“not Prime”);
status=1;
break;
}
if(status==0)
{
Console.Criteline(“PRIME”);
}
}

Hey, but i also think that it can be optimized to till sqrt of the number and i know the reason.