1

I have the following C++ code to find factorial of a number:

#include <iostream>
using namespace std;
int factorial(int n){
   if (n<=1)
   {return 1;
    
    }
    return n*factorial(n-1);
}
int main()
{
    int a;
    cout<<"Enter a no: ";
    cin>>a;
    cout<<"The value of "<<a<<"! is "<<factorial(a);

return 0;
}

It works fine for values upto 12! But show wrong values above it. e.g. -- 20! is showing -2102132736 ( a negative no)

,for some big values like 50! show 0.

What could be the probable reason ???

  • 1
    Use `long long int` – anirudh Jun 29 '21 at 09:35
  • 1
    Integers have limited capability. `int` typically has range from -2147483648 to 2147483647 . If you go beyond that, you get overflow and Undefined Behaviour follows. You can use `unsigned long long` instead of `int`, but that will only push the limit to 20. – Yksisarvinen Jun 29 '21 at 09:35
  • Related: [Factorial program in C is wrong after 20](https://stackoverflow.com/questions/35893305/factorial-program-in-c-is-wrong-after-20) – Yksisarvinen Jun 29 '21 at 09:38
  • The size of type int. It's maximum value, usually is 2^32 - 1.As soon as you reach overflow, it's unknown what will be result. Values greater than 13! are greater than 6227020800 – Swift - Friday Pie Jun 29 '21 at 09:39
  • 50! is a bit beyond the reach of `long long` as well. If you want to work with numbers like that, you could try `double` or if you want exact results, arbitrary precision integers (e.g. gmp library). –  Jun 29 '21 at 09:39
  • `int` supported by your compiler (or host) is presumably 32-bit. Calculating factorial of `13` will overflow a 32-bit integral type, causing undefined behaviour. You need to use a type that is *guaranteed* to represent a larger range (such as `long long`). Bear in mind that only increases the range of feasible values - `long long` is not required to be more than 64-bit, and a 64-bit integral type will overflow when calculating factorial of `21`. [Incidentally, an `int` is not guaranteed to have more than 16 bits - and that will overflow when computing factorial of `9`]. – Peter Jun 29 '21 at 11:30

1 Answers1

1

Although formally the behaviour on overflowing an int is undefined, modulo arithmetic on a number that's a power of 2 is a common treatment.

A number like 50! has as its many factors a large power of 2. This accounts for the zeros you are getting as output.

The solution is to use an arbitrary precision integer library. There's a good one in Boost.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483