Big Data factorial

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.