1

Possible Duplicate:
Calculating factorial of large numbers in C

Firstly, I am new to C++. I have tried below program to calculate factorial of any number.

#include <iostream>
using namespace std;
unsigned long factorial(unsigned long n){
   return n <= 1 ? 1 : n * factorial(n-1);
}

int main()
{
  cout << "Enter any Number to calculate factorial." <<endl;
  unsigned long n;
  cin >> n ;
  cout << factorial(n)    ;
}

If i give small numbers like 5,3,20 it returns me exact value. But if I give numbers like 34 etc.. It is returning me zero. I assume that it is exceeding the limit range. Please help me on this to return exact result whatever the number I enter.

Community
  • 1
  • 1
Exception
  • 8,111
  • 22
  • 85
  • 136

1 Answers1

7

Factorials are huge.

34! = 295232799039604140847618609643520000000

This barely fits into 128 bits. If your compiler supports a 128-bit number type, you can use it to calculate factorials up to 34. If not, or if you need anything larger, you will need to use some kind of bignum library.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243