HDU -- 1042

N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 91629 Accepted Submission(s): 27190

Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!

Input
One N in one line, process to the end of file.

Output
For each N, output N! in one line.

Sample Input
1
2
3

Sample Output
1
2
6
显而易见,这道题目的结果特别大,百度后找到一种解决方法:万进制。跟八进制、十进制、二进制差不多。但是计算方法不太一样。这里我就用网上找到一个例子:
107924372*15=1618865580。

首先存数:a[0]=4372,a[1]=792,a[2]=1。107924372,

从低位到高位每四位存到一个数组元素中。此时,总位数为3。a[1]*15=11880,a[1]=a[1]+6=11886。
进位为1,a[1]=1886。a[2]*15=15,a[2]=a[2]+1=16,进位为0。
输出:a[2],a[1],a[0]。
即为1618865580。

#include<stdio.h>
int factorial(int n)
{
    int a[10000+1] = {1}; // 数组,每一个数都是4位的;
    int digit = 1/*位数*/, carry/*进位*/, i, j;
    for (i = 2; i <= n; i ++)
    {
        carry = 0;
        for (j = 0; j < digit; j ++)
        {
            a[j] = a[j] * i + carry;
            carry = a[j] / 10000;
            a[j] %= 10000;
        }
        if (carry > 0)
            a[digit ++] = carry;
    } 
    printf ("%d", a[digit - 1]);
    for(i = digit - 2; i >= 0; i --)
        printf ("%04d", a[i]);
    printf("\n");

}
int main()
{
    int n;
    while (~scanf ("%d", &n))
        factorial(n);
    return 0;
 } 

猜你喜欢

转载自blog.csdn.net/hqzzbh/article/details/81046330