views:

85

answers:

2

i successfully complied the code:

#include <stdio.h>
#include <math.h>
int q;

int main()
{
    srand( time(NULL) );
    int n=3;
    q=ceil(sqrt(n));
    printf("%d\n %d\n", n,q);

    if(n == 2)
        printf("%d\n is prime", n);
    else if(n % 2 == 0.0 || n < 2)
        printf("%d\n is not prime", n);
    else
    {
        int x;
        for(x = 0; x < q; x++){
            if(n % x == 0)
            {
                printf("%d\n is not prime", n);
                return;
            }
            else
                printf("%d\n is prime", n);
        }
    }
}

but when i run it prints :Floating point exception

can u help me to fix this error

+6  A: 

It's caused by n % x, when x is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

General notes:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.
Matthew Flaschen
Addition: You get a *Floating point exception* since your computer does not have a special case for *integer division by 0*. A better description would be *Arithmetic exception*, but this misnomer has a long history and probably cannot be changed anymore.
Roland Illig
A: 

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

Andre Holzner