Search code examples
ccoredumpfloating-point-exceptions

Floating Point Exception with no float or double variable


I am getting a problem with following code that "Floating point exception, core dumped" but I have not even one float or double variable. By using checking printf, i observed that it happens in isPrimeFunction, where there execution jams.

/*
PROBLEM 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/


#include <stdio.h>

typedef int bool;
const bool true=1;
const bool false=0;

bool isPrime(long long int number) {
    long long int i;
    for(i=2; i < (number/2); i++) {
        if(number%i == 0) {
            return false;
        }
    }
    return true;
}   

int main() {
    long long int number, largest;
    number=600851475143;
    largest=0;
    int i;

    for(i=1; i <= (number/2); i++) {
        if((number % i) == 0) {
            if(isPrime(i) == true) {
                largest=i;
            }
        }
    }
    if(largest != 0)    
        printf("Largest prime factor is: %lli\n", largest);
    else
        printf("There is no prime factor of the number.\n");    

    return 0;
}

Solution

  • In main your i is an int and therefore most likely not big enough to fit number/2 which means that it's quite possible (although this is undefined behavior) that i will wrap and eventually end up being 0. number % i will then cause division by zero which is another undefined behavior but quite likely why your system generates a floating point exception (mine does).

    N.B. This is not a very good algorithm. Just count how many times you'll loop. With a number like 600 billion that you have even if it's prime and you never trigger the isPrime test inside the loop you're looking at runtimes close to an hour. Every time you hit the test inside the loop you're increasing your runtime by a lot.