Search code examples
c++intdoublefactorial

why using int64_t gives wrong result while double works as expected for simple integer multiplications


here is my code :

using integer = int64_t;

integer factorial(integer number) {
    return number <= 0 ? 1 : number * factorial(number - 1);
}

integer binomial_coefficent(integer n, integer r) {
    return factorial(n) / (factorial(r) * factorial(n - r));
}

int main()
{
    using namespace std;
    cout << binomial_coefficent(40, 20) << endl;
    return 0;
}

this prints

0

which is wrong answer but if i change integer type to double that will print 1.37847e+11 which is the correct answer,my question is why using int64_t gives me incorrect answer


Solution

  • and int64_t doesn't overflow either

    It does though. For debugging things like this, you can run this with -fsanitize=signed-integer-overflow (implied by -fsanitize=undefined) in GCC or clang to see:

    runtime error: signed integer overflow: 21 * 2432902008176640000 cannot be represented in type 'long'
    runtime error: signed integer overflow: 2432902008176640000 * 2432902008176640000 cannot be represented in type 'long'