``````#include "conio.h"
#include "stdio.h"
#include "math.h"

int isPrime(int n)
{
int i,isTrue=1;
for(i=2; i<(int)sqrt(n); i++)
if(n%i==0)
return 0;
else return 1;
}

int main()
{
int N;
printf("Enter n: ");
scanf("%d",&N);
if(isPrime(N))
printf("prime");
else
printf("Not prime\n");
getch();
return 0;
}``````

here is my source code, but when i test , sometimes it's true sometimes it's false. I don't know what is my mistake
Thanks a lot!

## All 4 Replies

Your `isPrime` function will return 0 for even-number and return 1 for odd-number because your loop always end at the first loop (because you always return a value at the first loop.)

``````int i;
for(i=2; i<(int)sqrt(n); i++) {
if(n%i==0) return 0;
}
return 1;``````

You can also further optimize your code by:

``````int i;
int k = (int)sqrt(n);

for(i=2; i<k; i++) {
if(n%i==0) return 0;
}
return 1;``````

our isPrime function will return 0 for even-number and return 1 for odd-number because your loop always end at the first loop (because you always return a value at the first loop.)

``````int i;
for(i=2; i<(int)sqrt(n); i++) {
if(n%i==0) return 0;
}
return 1;
``````

You can also further optimize your code by:

``````int i;
int k = (int)sqrt(n);

for(i=2; i<k; i++) {
if(n%i==0) return 0;
}
return 1;
``````

I try it again but the results sometimes true sometimes wrong

It should actually be "<= k" rather than less than.

Use 9 as an example and you'll see. The for loop ends and fails to mod 9 against 3, hence returning a value of 1.

It should actually be "<= k" rather than less than.

Use 9 as an example and you'll see. The for loop ends and fails to mod 9 against 3, hence returning a value of 1.

Ukie! Thank you very much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.