首页 > ACM题库 > HDU-杭电 > HDU 1066 Last non-zero Digit in N!-高精度-[解题报告] C++
2013
11-26

HDU 1066 Last non-zero Digit in N!-高精度-[解题报告] C++

Last non-zero Digit in N!

问题描述 :

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 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!.

输出:

For each integer input, the program should print exactly one line of output containing the single last non-zero digit of N!.

样例输入:

1 
2 
26 
125 
3125 
9999

样例输出:

1
2
4
8
2
8

这道题被搁置了很久,又拿来做,终于搞懂了。

分析:

1.末尾的0是由2和5相乘产生的,而2的个数多于5的个数。

2.将5的倍数提取出来:令An为提取后的结果,函数f(x)表示x的最右非0位,N! = 5 * (floor(N/5)!) * An, f(N!) = f(floor(N/5)!)*f(5*An);

显然这是一个递归式,那么怎样求 f(5*An)?

易知,An中没有末尾0,则只需在An中提取出相应个数的2,即An除以相应个数的2。

处理出前100(A0 ~ A99 除以相应个数的2):

 

 

0: 1
1: 1
2: 2
3: 6
4: 4
5: 2
6: 2
7: 4
8: 2
9: 8
10: 4
11: 4
12: 8
13: 4
14: 6
15: 8
16: 8
17: 6
18: 8
19: 2
20: 6
21: 6
22: 2
23: 6
24: 4
25: 2
26: 2
27: 4
28: 2
29: 8
30: 4
31: 4
32: 8
33: 4
34: 6
35: 8
36: 8
37: 6
38: 8
39: 2
40: 6
41: 6
42: 2
43: 6
44: 4
45: 2
46: 2
47: 4
48: 2
49: 8
50: 4
51: 4
52: 8
53: 4
54: 6
55: 8
56: 8
57: 6
58: 8
59: 2  

 

 

规律是很明显的。因为N可能很大,需要用大数除法计算N/5。

#include <stdio.h>
#include <string.h>
#define MAXN 10000

char n[10000];

int lastdigit(char* buf)
{
    const int mod[21]={6,6,2,6,4,2,2,4,2,8,4,4,8,4,6,8,8,6,8,2,1};
    int len=strlen(buf),a[MAXN],i,c,ret=1;
    if(len==1) return mod[(buf[0]-'0')<=1?20:(buf[0]-'0')];
    for (i=0;i<len;i++) a[i]=buf[len-1-i]-'0';
    for (;len;len-=!a[len-1])
    {
        ret=ret*mod[a[1]%2*10+a[0]]%10;
        for (c=0,i=len-1;i>=0;i--)
            c=c*10+a[i],a[i]=c/5,c%=5;
    }
    return ret;
}


int main()
{
    while(scanf("%s",n)!=EOF)
        printf("%d\n",lastdigit(n));
    return 0;
}

 


  1. 这道题目虽然简单,但是小编做的很到位,应该会给很多人启发吧!对于面试当中不给开辟额外空间的问题不是绝对的,实际上至少是允许少数变量存在的。之前遇到相似的问题也是恍然大悟,今天看到小编这篇文章相见恨晚。