# Thread: Prime number calculator, can't seem to find bug?

1. ## Prime number calculator, can't seem to find bug?

Hi everyone, I am trying to practice C. I wrote a prime-or-composite calculator, but my output always ends up suggesting the number is prime, when in fact it should be composite. I've looked over my code numerous times and I've compared it to others and I still don't see what I am doing wrong. If someone else could look at my code and inform me as to what is wrong with my code that would be great - a second pair of eyes always help. By the way, I know I don't have to utilize pointers to accomplish this program, but I'm just trying to get some practice with them.

Here is my code:

Code:
```#include <stdio.h>

int main()
{
int num, *pnum;
int i, flag = 0;

pnum = &num;

printf("\nEnter any number: ");
scanf("%d", pnum);

while (*pnum != -1)
{
if (*pnum == 0 || *pnum == 1) {
printf("\n\t%d is neither prime nor composite", *pnum);
} else if (*pnum == 2) {
printf("\n\t%d is prime", *pnum);
} else {
for (i = 2; i < ((*pnum) / 2); i++ )
{
if (*pnum % i == 0)
flag = 1;
break;
}

if (flag == 0) {
printf("\n\t%d is prime", *pnum);
} else {
printf("\n\t%d is composite", *pnum);
}
}

flag = 0;
printf("\n\nEnter any number: ");
scanf("%d", pnum);

}

return 0;
}```

output:

Enter any number: 0

0 is neither prime nor composite

Enter any number: 1

1 is neither prime nor composite

Enter any number: 2

2 is prime

Enter any number: 3

3 is prime

Enter any number: 4

4 is prime

Enter any number:

2. It says 4 is prime because your for loop only goes as long as i is LESS THAN half the number, so it never tests 4 with the divisor 2. The condition needs to be <=. But actually, you only need to test up to the square root, which is a lot less than half for bigger numbers.

And if you test for divisibility by 2 separately then you can speed up the loop by only testing odd numbers.
Code:
```    int is_prime = 1;
if (num % 2 == 0)
is_prime = (num == 2);
else {
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) {
is_prime = 0;
break;
}
}
printf("\t%d is %s\n", num, is_prime ? "prime" : "composite");```

3. Originally Posted by john.c
It says 4 is prime because your for loop only goes as long as i is LESS THAN half the number, so it never tests 4 with the divisor 2. The condition needs to be <=. But actually, you only need to test up to the square root, which is a lot less than half for bigger numbers.

And if you test for divisibility by 2 separately then you can speed up the loop by only testing odd numbers.
Code:
```    int is_prime = 1;
if (num % 2 == 0)
is_prime = (num == 2);
else {
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) {
is_prime = 0;
break;
}
}
printf("\t%d is %s\n", num, is_prime ? "prime" : "composite");```
Thanks John, appreciate it.

Popular pages Recent additions