0

This piece of code is giving 'signal: floating point exception (core dumped)' error.

#include <stdio.h>

int fact(int n);
int comb(int x, int y);
int greater(int x, int y);

int main() {
    int count = 0;
    for (int n = 1; n <= 100; n++) {
        for (int r = 0; r <= n; r++) {
            if (greater(n, r)) {
                count++;
            }
        }
    }
    printf("%d\n", count);
    return 0;
}

int fact(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * fact(n - 1);
}

int comb(int x, int y) {
    return fact(x) / (fact(x - y) * fact(y));
}

int greater(int x, int y) {
    if (comb(x, y) > 1000000) {
        return 1;
    }
    return 0;
}

The 'comb' function, which returns the combination of two numbers, is always supposed to return an integer. I also don't think I'm dividing by zero anywhere because I already added the condition that fact(0) returns 1. What could be the cause and how to fix it?

1 Answers1

2

The “floating point exception” is a legacy of old computer hardware and software. What it actually indicates in this case is division by zero.

Division by zero occurs because the numbers you are using exceed the range representable in int. Some of the overflows produce zero as a result, and then fact(x) / (fact(x - y) * fact(y)) divides by zero.

You will not be able to compute comb(100, 50) using just ordinary int arithmetic. You will need to write or use multiprecision software or will need to approximate the value using floating-point arithmetic.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312