3

In this code:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

int main (int argc, char ** argv) {
    uint64_t bignum = 600851475143;
    int is_prime = 0;
    uint64_t result = 0;
    uint64_t i = 0;
    uint64_t j = 0;

    for (i = 0; i < bignum; i++) {
        if (bignum % i == 0) {
            is_prime = 1;
            for (j = 0; j < i; j++) {
                if (i % j == 0) {
                    is_prime = 0;
                    break;
                }
            }
            if (is_prime) {
                result = i;
            }
        }
    }

    printf("The largest prime factor of the number %lu is %lu.\n", bignum, result);

}

when compiling with:

$ gcc -Wall -g 3.c -o 3 -lm

I get a "floating point exception" upon running the resulting executable. There are no floating point numbers in the code. What is going wrong here, and what do I need to do to resolve the problem?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
connoraw
  • 173
  • 1
  • 2
  • 11

2 Answers2

12

Divide by 0 is reported as a "floating point exception". Don't ask me why.

You're dividing by 0 in at least two places. Note that the modulo operator % counts as division.

user3386109
  • 34,287
  • 7
  • 49
  • 68
2

On the first iteration of the loop, i is 0, so bignum % i is a division by 0, which is what causes the floating point exception. The same happens with j in your inner loop.

Since you're testing for primality, dividing by 0 or by 1 doesn't make sense, so start with 2. Also, you should stop at sqrt(bignum).

uint64_t limit = sqrt(bignum);
for (i = 2; i < limit; i++) {
    ...
    for (j = 2; j < i; j++) {
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Also, there is no point in testing 4, 6, 8, etc. Do a test for 2, then make your for-loop: `for(i = 3; i < limit; i+=2)`, effectively testing 3, 5, 7, 9, etc.... – abelenky Jan 12 '18 at 21:48