Under normal circumstances, a factorial is multiplied by 1 by 2 by 3 by 4 until it reaches the required number, that is, the natural number N factorial.
The following code uses int to calculate the factorial result:
int SmallFactorial(int number){ int sum = 1; for (int i = 1; i <= number; i++) { sum *= i; } return sum;}
Test results:
When the factorial is very small, it is normal that there is no problem.
Here 32! If the value exceeds the int range, an error occurs.
As the natural number N in the factorial grows, it is 1000 !, 10000! Such factorial cannot be saved by simple types, but large numbers can be simulated through arrays.
The following uses Arrays for implementation:
// Calculate the number of digits of the factorial int length = (INT) (Number * Math. log10 (number + 1)/2); // The array int [] dashu = new int [length]; dashu [length-1] = 1 ;; // loop for (INT I = 2; I <= number; I ++) {// multiply the number in the array by I for (Int J = length-1; j> = 0; j --) {If (dashu [J] = 0) {continue;} dashu [J] = dashu [J] * I ;} // process the number of arrays. If it is greater than 10, it is carried up for (Int J = length-1; j> 0; j --) {If (dashu [J] = 0) {continue;} dashu [J-1] + = dashu [J]/10; dashu [J] = dashu [J] % 10 ;}} // convert the result foreach (int I in dashu) {if (I = 0 & SB. length = 0) continue; sb. append (I. tostring ());}
100! The result is as follows:
1000! The result is as follows:
The number is already large.
However, the computation here is not optimized, but it is enough to cope with common computation.
10000! I want to test it for nearly 6 S, but 100000! The page cannot be displayed, and the calculation time times out.
From the calculation of factorial, we learned how to process large numbers.