hdu 1042 N! 高精度运算

N!

                                                                             Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

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
 
题目分析:用数组模拟乘法。让a[0]保存结果的各位,a[1]是十位,a[2]是百位……(为什么要逆序表示呢?因为如果按照从高到低的顺序储存,一旦进位的话就……),则每次只需要模拟手算即可完成n!。在输出时需要忽略前导0.注意,如果结果本身就是0,那么忽略前导0后将什么都不输出。所幸n!肯定不等于0,因此本题可以忽略这个细节。
#include<stdio.h>
#include<string.h>
const int maxn=40000;  /*数组不能太小,小了存不下*/
int a[maxn];
int main()
{
    int i,j,n;
    while(~scanf("%d",&n))
    {
        memset(a,0,sizeof(a));
        a[0]=1;
        for(i=2;i<=n;i++)
        {
            int c=0;  /*保存进位*/
            for(j=0;j<maxn;j++)
            {
                int s=a[j]*i+c;
                a[j]=s%10;
                c=s/10;
            }
        }
        for(j=maxn-1;j>=0;j--)  /*去掉前导零*/
            if(a[j])
                break;
        for(i=j;i>=0;i--)
            printf("%d",a[i]);
        printf("
");
    }
    return 0;
}


原文地址:https://www.cnblogs.com/javawebsoa/p/3244051.html