Accurate value of factorial of N for large numbers (less than 10000) (efficiency)

 51Node - 1057


Split the result, the width of the split can be 4, 5, 6, 7, 8..

Store the result in a[100000]; In this array, if each element stores 5 bits of the result, then this array can store 500,000 digits, which is definitely large enough.

Like 10! = 3628800 ..

Then the storage situation in the array a [] is a [ 0 ] = 28800,, a [ 1 ] = 36..

Another example is a number 1 0 9 8 7 6 5 4 3 2 1 . Its storage condition is. . a[ 0 ] = 54321 , a[ 1 ] = 09876 , a[ 2 ] = 1....

The operation is like multiplying large numbers. Each element must be multiplied. If the element exceeds 5 digits, it will be carried and added to the next element.

And so on. .

Finally output the array from back to front.

It should be noted that if the width of the division is 5, except the last element of the array is not sure whether it is 5 bits, the other output should be "%05d". . ! !

#include <cstdio>
#include <algorithm>
#include <iostream>

using namespace std;

int a[100000]={1,0};
int n, i, c, len, j;

intmain()
{
    scanf("%d",&n);
    len = 1; // len is used to record how many elements there are in a.
    for (i = 2;i <= n; ++ i)
    {
        c = 0; // c is the number to carry
        for (j = 0;j < len;++ j)
        {
            a[j] = (a[j] * i + c ); // Note that each multiplication requires +c (plus the last carry)
            c = a[j]/100000; //If the result of the operation is less than 5 bits, c is 0.
            a[j] %= 100000; // Guaranteed to store 5 digits per element
        }
        if(c > 0) // After a loop, if c > 0, it means more than 5 digits and a carry is required
        {
            a[j] = c; // a adds a new element to the number of carry bits
            ++len; // Then len++ is needed to record the number of elements. .
        }
    }
    printf("%d",a[--len]); // Enter the highest digits first, not sure how many, don't care.
    while(len)
        printf("%05d", a[--len]); // The following are all 5 digits, pay attention to the format.
    printf("\n");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326483255&siteId=291194637