# Prime number function gives garbage value

This is a discussion on Prime number function gives garbage value within the C Programming forums, part of the General Programming Boards category; so i have to write a much larger program, but i am starting with the prime function to call first. ...

1. ## Prime number function gives garbage value

so i have to write a much larger program, but i am starting with the prime function to call first. anyway, it appears work work properly however, when it does recognize that it is prime, it prints a garbage value of like 13978 instead of returning 1. if anyone can see the mistake please let me know.

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

int isprime(int n);

int main()
{

int n;

printf("Enter a number:\n");
scanf("%d", &n);

printf("%d\n", isprime(n));

}

int isprime(int n)
{
int i, z;

for(i=2; i<n; i++)
{
if(n%i==0)
{
z = 0;
}

if(i*i>n)
{
z = 1;
}
}

return z;
}```

2. For me, it returned "1" for every number above 2 it seems. Edit: iMalc is correct: there is a case where both ifs don't go through and thus you get an unitialized value (could be anything). Duh.

I think the problem is your if(i*i>n) ? Is that an optimization, because the for loop will still run, so it's not much of an optimization. You should just return the value directly. Also, please indent the code inside of your if statements, it's standard formatting and easier to read.

Here's a quick version I wrote, with a few changes (needs math.h for sqrt and stdlib.h for abs):
Code:
```int isprime(int n)
{
int i;

if(n < 0)
n=abs(n); //incase it's negative

if(n == 2) // 2 is prime (2*1, 1*2)
return 1;

if(n == 1 || n % 2 == 0) //if divisible by 2, not prime.
return 0; //1 is not prime by definition

for(i = 3; i < (sqrt(n) + 1); i+=2) //skip every 2, we already checked if it was divisible by 2
if(n % i == 0)				//Also: we only have to go up to sqrt(n)+1 (4*4 = 16, so if we go to the sqrt)
return 0;				//we are sure to find if it's prime or not

return 1;
}```

3. If neither if-condition in the for-loop is ever true, what value would you expect z to have?

Once you know the number is composite, why would you have you loop keep going? Why not break out straight away.

4. @jbone0881: initialize z with some value soon after you start implementing function.....