HDUOJ-----1066Last non-zero Digit in N!

Last non-zero Digit in N!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5596    Accepted Submission(s): 1382


Problem Description
The expression N!, read as "N factorial," denotes the product of the first N positive integers, where N is nonnegative. So, for example,
N N!
0 1
1 1
2 2
3 6
4 24
5 120
10 3628800

For this problem, you are to write a program that can compute the last non-zero digit of the factorial for N. For example, if your program is asked to compute the last nonzero digit of 5!, your program should produce "2" because 5! = 120, and 2 is the last nonzero digit of 120.
 
Input
Input to the program is a series of nonnegative integers, each on its own line with no other letters, digits or spaces. For each integer N, you should read the value and compute the last nonzero digit of N!.
 
Output
For each integer input, the program should print exactly one line of output containing the single last non-zero digit of N!.
 
Sample Input
1
2
26
125
3125
9999
 
Sample Output
1
2
4
8
 
2
8
 
Source
经过细致的观察,发现n!的阶乘,要求其最后一位非0,便是要去掉所有的0 ...比如
6!=720..
我们在循环的时候,只需要取其长度取摸就可以了,ans%strlen(itoa(6));
代码如下.
 1 #include<stdio.h>
 2 int main()
 3 {
 4     int n,i;
 5     _int64 ans;
 6     while(scanf("%d",&n)!=EOF)
 7     {
 8         ans=1;
 9        for(i=2;i<=n;i++)
10         {
11             ans*=i;
12             while((ans%10)==0)    ans/=10;
13             ans%=100000000;
14         }
15            while((ans%10)==0)    ans/=10;
16             ans%=10;
17         printf("%I64d
",ans);
18     }
19     return 0;
20 }

代码精简,但是复杂度为O(n)。。。提交的时候果断的tle了,爱,好忧伤呀~~~!,后来想了想,能否将其优化勒!

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define maxn 1000
 4 const int mod[20]={1,1,2,6,4,2,2,4,2,8,4,4,8,4,6,8,8,6,8,2};
 5 char str[maxn];
 6 int a[maxn];
 7 int main()
 8 {
 9     int len,i,c,ret;
10     while(scanf("%s",str)!=EOF)
11     {
12        len=strlen(str);
13         ret=1;
14     if(len==1) printf("%d
",mod[str[0]-'0']);
15     else
16     {
17      for(i=0;i<len;i++)
18         a[i]=str[len-1-i]-'0';    //将其转化为数字以大数的形式
19      for( ;  len>0; len-=!a[len-1])
20      {
21        ret=ret*mod[a[1]%2*10+a[0]]%5;
22      for(c=0, i=len-1 ;i>=0;i--)
23      {
24         c=c*10+a[i];
25         a[i]=c/5;
26         c%=5;
27      } 
28     }
29     printf("%d
",ret+ret%2*5);
30     }
31     }
32     return 0;
33 }
View Code
原文地址:https://www.cnblogs.com/gongxijun/p/3506680.html