[c] Floating point exception

I successfully complied this 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 my code I get the following error:

Floating point exception

What does this error mean and how can I fix it?

This question is related to c floating-point

The answer is


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


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.

http://en.wikipedia.org/wiki/Division_by_zero

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0 IS division by zero and as such, will trigger a SIGFPE being thrown.