Factorials

The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit integer on most computers, and 70! is too large for most floating-point variables. Your task is to find the rightmost non-zero digit of n!. For example, 5! = 1 * 2 * 3 * 4 * 5 = 120, so the rightmost non-zero digit of 5! is 2. Likewise, 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040, so the rightmost non-zero digit of 7! is 4.

PROGRAM NAME: fact4

INPUT FORMAT

A single positive integer N no larger than 4,220.

SAMPLE INPUT (file fact4.in)

7

OUTPUT FORMAT

A single line containing but a single digit: the right most non-zero digit of N! .

SAMPLE OUTPUT (file fact4.out)

4

思路:hdu上有比它更变态的题,给个网址,上面讲的很详细。
http://blog.csdn.net/yibcs/article/details/8040862
Executing...
   Test 1: TEST OK [0.000 secs, 3228 KB]
   Test 2: TEST OK [0.000 secs, 3228 KB]
   Test 3: TEST OK [0.000 secs, 3228 KB]
   Test 4: TEST OK [0.000 secs, 3228 KB]
   Test 5: TEST OK [0.000 secs, 3228 KB]
   Test 6: TEST OK [0.000 secs, 3228 KB]
   Test 7: TEST OK [0.000 secs, 3228 KB]
   Test 8: TEST OK [0.000 secs, 3228 KB]
   Test 9: TEST OK [0.000 secs, 3228 KB]
   Test 10: TEST OK [0.000 secs, 3228 KB]

All tests OK.
 1 /*
 2 ID:wuhuaju2
 3 PROG:fact4
 4 LANG:C++
 5 */
 6 
 7 #include <cstdio>
 8 #include <iostream>
 9 #include <cstdlib>
10 #include <algorithm>
11 #include <cstring>
12 using namespace std;
13 
14 const int x[]={6,6,2,6,4,2,2,4,2,8,4,4,8,4,6,8,8,6,8,2};
15 const int maxn=100;
16 int a[maxn+10];
17 char s[maxn];
18 int n,t,l,e,beg,ans,tt;
19 
20 
21 
22 void close()
23 {
24     fclose(stdin);
25     fclose(stdout);
26     exit(0);
27 }
28 
29 void work()
30 {
31 }
32 
33 void init ()
34 {
35 freopen("fact4.in","r",stdin);
36 freopen("fact4.out","w",stdout);
37     scanf("%s",s);
38      l=strlen(s);
39      if (l==1 && s[0]=='1')
40      {
41          cout<<1<<endl;
42          close();
43      }
44      ans=1; int cnt=0;
45      e=maxn; beg=e-l+1;
46     // printf("e:%d beg:%d \n",e,beg);
47      for (int i=l-1;i>=0;i--)
48      {
49          a[e-cnt]=s[i]-'0';
50          cnt++;
51      }
52      while (beg<=e)
53      {
54          t=a[(e-1)] % 2 * 10+a[e];
55          ans=(ans*x[t]) % 10;
56          t=0;
57          for (int i=e;i>=beg;i--)
58          {
59              t=a[i]*2 /10;
60              a[i]=(a[i]*2+tt) % 10;
61              tt=t;
62          }
63          if (t>=1)
64          {
65              beg--;
66              a[beg]=1;
67          }
68          e--;
69      }
70      cout<<ans<<endl;
71 }
72 
73 int main ()
74 {
75     init();
76     work();
77     close();
78     return 0;
79 }

 

posted on 2013-01-31 11:24  cssystem  阅读(204)  评论(0)    收藏  举报