1042-N!

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


“10000的阶乘怎么算?

答:“10000”这个数字太大了,无论用什么数据类型保存结果都会溢出。现在使用数组来模拟数字,这样无论结果数字有多大,只要数组的长度够长就能表示出来,用这个办法可以进行大数据的运算。

下面我以10000的阶乘为例,10000的阶乘最后的结果长度是35660位的,所以我在此定义了一个40000个成员的数组。

算法流程:

1、先定义一个足够长的数组;

2、定义一个含40000个元素的数组:int result[40000];我的目的就是将结果的每一位上的数字保存到一个数组成员中。

例如:把124保存至数组中,保存结果应该是:result[0] 4;result[1] 2;result[2] 1

一个int型数据存放一个小于10的数是绝对不会溢出!

把整个数组看成一个数字,这个数字和一个数相乘的时候,需要每一位都和这个乘数进行相乘运算还需要把前一位的进位加上。运算方法和小学数学是一样的,乘积的个位是当前位上应该表示的数字,10位以上的需要进位。因为乘数不可能大于10000,所以乘数和一个小于10的书相乘的时候不会大于100000,再加上前一位的进位用一个int型数据来保持这个结果就没有问题。

写法如下:
int 结果 = result[x] * 乘数 + 进位;
每一位的计算结果有了,把这个结果的个位数拿出来放到这个数组元素上:
result[x] = 结果%10;
接下来的工作就是计算出进位:
进位 = 结果 / 10;
这样一位一位的把整个数组计算一遍,最后可能还有进位,用同样的方法,把进位的数值拆成单个数字,放到相应的数组元素中。

转载代码:

#include<stdio.h>  
int main()  
{  
   int carry, n, j;  
   int a[40001];  
   int digit;  
   int temp, i;  
   printf("Please enter a integer:");  
   while (scanf("%d", &n) != EOF){  
      a[0] = 1;  
      digit = 1;  
      for (i = 2; i <= n; i++)  
      {  
          for (carry = 0, j = 1; j <= digit; ++j)  
          {  
              temp = a[j - 1] * i + carry;  
              a[j - 1] = temp % 10;  
              carry = temp / 10;  
          }  
         while (carry)  
        {  
            //digit++;  
            a[++digit - 1] = carry % 10;  
            carry /= 10;  
        }  
     }  

     for (int k = digit; k >= 1; --k)  
          printf("%d", a[k - 1]);  
     printf("\n");  
     printf("The length of result is:%d\n", digit);  
  }  
  return 0;  
}  

本题AC代码:

#include<cstdio>
#include<cstring>
#include<cmath>

#define N 1000000
int a[N];

int main()
{
    int n;

    while (scanf ("%d",&n) != EOF)
    {
        a[0] = 1;
        int digit = 1;
        int i,j;
        int x,ans;

        for (i=1; i<=n; i++)
        {
            x = 0;
            for (j=1; j<=digit; j++)
            {
                ans = a[j-1]*i+x;
                a[j-1] = ans%10;
                x = ans/10;
            }
            while (x)
            {
                a[digit] = x%10;
                digit++;
                x /= 10;
            }
        }

        for (i=digit-1; i>=0; i--)
        {
            printf ("%d",a[i]);
        }
        printf ("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章