This is a factorial program which uses array to calculate large factorials.
The problem is sometimes if I enter 1000, it gives the output but stops working there after. I tried it with 2000, 3000, it works fine. I cant understand its erratic behaviour? Is there any problem with my processor? I

#include <cmath>
#include <iostream>

using namespace std;

int main()
{
  unsigned int nd, nz;   
  unsigned char *ca;     
  unsigned int j, n, q, temp;
  int i;
  double p;

  while(true)
  {
    cout << "\nEnter an integer to calculate factorial (0 to exit): ";
    cin >> n;

    if (n == 0) break;

    //calculate nd = the number of digits required
    p = 0.0;
    // p is really log10(n!)
    for(j = 2; j <= n; j++)
    {
      p += log10((double)j);   // cast to double
    }
    nd = (int)p + 1;
    // allocate memory for the char array
    ca = new unsigned char[nd];
    if (!ca)
    {
      cout << "\n Memory allocation error!!!\n";
      exit(0);
    }
    //initialize char array
    for (i = 1; i < nd; i++)
    {
      ca[i] = 0;
    }
    ca[0] = 1;

    // put the result into a numeric string using the array of characters
    p = 0.0;
    for (j = 2; j <= n; j++)
    {
      p += log10((double)j);   // cast to double!!!
      nz = (int)p + 1;         // number of digits to put into ca[]
      q = 0;                   // initialize remainder to be 0
      for (i = 0; i <= nz; i++)
      {
        temp = (ca[i] * j) + q;
        q = (temp / 10);
        ca[i] = (char)(temp % 10);
      }
    }

    cout << "\nThe Factorial of " << n << " is: ";
    // the factorial is stored in reverse, spelling it from the back
    for( i = nd - 1; i >= 0; i--)
    {
      cout << (int)ca[i];
    }
    cout << endl;

    // free-ing up allocated memory
    delete []ca;
  }

  return 0;
}
Comments
Same problem !

1000! == 4.023872601e+2567 - a value that will overflow ANY normal computer numeric variable. My guess is that 2000, 3000, etc worked because of numeric overflow on the integers resulted in a valid (NOT correct) value. To work with such large numbers, you need specialized math software libraries, such as Boost, that support arbitrary precision math. IE, you are trying to use a rubber-band powered airplane model to achieve Mars orbit - ain't gonna work!

Sometimes the program spits out the requried result and then stops working, and sometimes it works fine with very large value ( I have even printed factorial of 10,000 ).

And why there should be any numeric over flow ? didn't understand that part. I'm just printing an array which is dynamically created.

This article has been dead for over six months. Start a new discussion instead.