This was a problem with the teacher when I was in college.
In C ++, it is impossible to accurately calculate the factorial of more than 20 using common data types. In the following example, we use an array to implement any factorial of less than 500. If we calculate a larger number, we can also implement it, but it takes a little longer.
// The following is the program code
# Include <iostream>
Using namespace STD;
Const int max = 10000;
Template <class typename>
Class fact
{
Public:
FACT (typename F): Value (f)
{
For (INT I = 0; I <Max; I ++)
{
Arr [I] = 0;
}
Arr [MAX-1] = 1;
}
// Calculate the factorial
Void calc ()
{
Int I = 0;
Int J = 0;
For (I = 1; I <= value; I ++)
{
// Calculate the factorial
For (j = MAX-1; j> = gettop (); j --)
{
Arr [J] * = I;
}
// Separate the data so that each data has only one digit
For (Int J = MAX-1; j> = gettop (); j --)
{
Arr [J-1] + = arr [J]/10;
Arr [J] = arr [J] % 10;
}
}
}
// Print the result
Void print ()
{
For (INT I = gettop (); I <Max; I ++)
{
Cout <arr [I];
}
Cout <Endl;
}
// Return to the top of the current data
Int gettop ()
{
Int nstart = max;
For (INT I = 0; I <Max; I ++)
{
If (ARR [I]> 0)
{
Nstart = I;
Break;
}
}
Return nstart;
}
PRIVATE:
Typename arr [Max];
Typename value;
};
Int main ()
{
Fact <int> F (100 );
F. Calc ();
F. Print ();
System ("pause ");
Return 0;
}