#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
Please help me solve it
Thanks a lot!

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.)

Try this one instead:

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.)

Try this one instead:

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

Edited 3 Years Ago by Reverend Jim: Fixed formatting

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.

Edited 7 Years Ago by Chilton: n/a

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!

This question has already been answered. Start a new discussion instead.