joj1386

 1386: 500!


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s 8192K 3081 552 Standard

In these days you can more and more often happen to see programs which perform some useful calculations being executed rather then trivial screen savers. Some of them check the system message queue and in case of finding it empty (for examples somebody is editing a file and stays idle for some time) execute its own algorithm.

As an examples we can give programs which calculate primary numbers.

 


One can also imagine a program which calculates a factorial of given numbers. In this case it is the time complexity of order O(n) which makes troubles, but the memory requirements. Considering the fact that 500! gives 1135-digit number no standard, neither integer nor floating, data type is applicable here.

 


Your task is to write a programs which calculates a factorial of a given number.

Assumptions: Value of a number "n" which factorial should be calculated of does not exceed 500.

Input

Any number of lines, each containing value "n" for which you should provide value of n!

Output

2 lines for each input case. First should contain value "n" followed by character `!'. The second should contain calculated value n!. Mind that visually big numbers will be automatically broken after 80 characters.

Sample Input

 

10
30
50
100

Sample Output

10!
3628800
30!
265252859812191058636308480000000
50!
30414093201713378043612608166064768844377641568960512000000000000
100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915
608941463976156518286253697920827223758251185210916864000000000000000000000000



就是求大数阶乘,注意80个一换行。还有,白书里的阶乘算法会超时。
 1 #include <stdio.h>
2 #include <string.h>
3
4 const int MAX = 1300;
5
6 int s[MAX];
7
8 int main(void)
9 {
10 int i, j, n, tmp, cnt, len;
11
12
13 while (scanf("%d", &n) == 1)
14 {
15 memset(s, 0, sizeof(s));
16
17
18 s[0] = 1;
19 len = 0;
20
21 for (i=2; i<=n; i++) //i与每一位乘
22 {
23 cnt = 0;
24 for (j=0; j<=len; j++)
25 {
26 tmp = s[j]*i+cnt;
27 s[j] = tmp % 10;
28 cnt = tmp / 10;
29 }
30
31 while (cnt) //处理进位
32 {
33 s[j++] = cnt % 10;
34 cnt /= 10;
35 len = j - 1; //记录当前最高位
36 }
37 }
38
39
40 printf("%d!\n", n);
41
42 int k=1;
43 for (i=len; i>=0; i--,k++)
44 {
45 printf("%d", s[i]);
46 if (k%80==0 && i)
47 {
48 printf("\n");
49 }
50 }
51 printf("\n");
52 }
53
54
55 return 0;
56 }

posted @ 2012-02-16 17:40  漂木  阅读(188)  评论(0编辑  收藏  举报