1

This is a function I made to calculate the factorial of a number

#include <iostream>
using namespace std;
int fact(int n) {
    if (n < 0) {
        cout << "Negative values not allowed";
        exit(4);
    }
    if (n == 0 || n == 1)
        return 1;
    else
        return n * fact(n - 1);
}

Now for some reason this code gives me correct answers up to x=12 (I used wolfram to check) after that it gives me wrong answers which is very strange why is that ?

  • 1
    `std::cout << std::numeric_limits::max() << '\n';` will show you the maximum value an `int` can hold. – Ted Lyngmo Jan 24 '22 at 13:03
  • 1
    `unsigned long long fact(int n)`{ ... }` will allow you to compute higher value of the factorial. – BNilsou Jan 24 '22 at 13:04
  • Your result is too big for a 32bit integer and [overflows](https://en.cppreference.com/w/c/language/operator_arithmetic) – eike Jan 24 '22 at 13:05
  • @TedLyngmo so after the numeric limit does it just give random answers ? because it gives me inaccurate numbers then at bigger values of x it gives me 0 – Youssef Mohamed Jan 24 '22 at 13:07
  • 1
    After you've passed the limit your program has undefined behavior because of signed integer overflow. With undefined behavior your program could do just about anything. – Ted Lyngmo Jan 24 '22 at 13:08
  • The behaviour of `int` overflow is undefined. What probably happens is the result is computed mod 2**32. By then your factorial is a multiple of a large power of 2, which explains the attaining of 0. – Bathsheba Jan 24 '22 at 13:13
  • 1
    @FadedYoussef -- [Use a big integer type](https://stackoverflow.com/questions/67630357/c-factorial-of-number-100/67630658#67630658). – PaulMcKenzie Jan 24 '22 at 13:43

0 Answers0