Just the Facts

Just the Facts

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 15   Accepted Submission(s) : 9
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 any factorial for (0 <= N <= 10000). 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 not exceeding 10000, 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. Each line of output should contain the value N, right-justified in columns 1 through 5 with leading blanks, not leading zeroes. Columns 6 - 9 must contain " -> " (space hyphen greater space). Column 10 must contain the single last non-zero digit of N!.
 

 

Sample Input
1
2
26
125
3125
9999
 

 

Sample Output
    1 -> 1
    2 -> 2
   26 -> 4
  125 -> 8 
 3125 -> 2 
 9999 -> 8
 

 

Source
PKU
输入一个数字N,计算1阶乘到N,求出最末位非0数字输出。
该题的难点在意,需要在每一次的阶乘的时候(ID[i]+=(ID[i-1]*i);),把末尾非零的数组都去掉,保留非零数值,并且最后还得取模10000,防止下一次数据相乘过大溢出,依次更新到题目所要求的最大范围10000。即可。在每次输出的时候,就可以直接输出该末尾非零数值了的。
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #define CLR(a) memset(a,0,sizeof(a))/*初始化*/
 5 main()
 6 {
 7    int Num,ID[11000],i;
 8    CLR(ID);
 9    ID[0]=0;ID[1]=1;
10    for(i=1;i<=10000;i++)
11     {
12         ID[i]+=(ID[i-1]*i);     /*保存每一次阶乘的数值*/
13         while(ID[i]%10==0&&ID[i]>=10)/*记录每一个末尾非零数值*/
14             ID[i]/=10;
15         ID[i]=ID[i]%100000;     /*防止下次数据相乘过大,溢出*/
16     }
17     while(scanf("%d",&Num)!=EOF)
18     {
19         printf("%5d -> %d\n",Num,ID[Num]%10);/*直接输出该阶乘结果的个位数*/
20     }
21     return 0;
22 }
View Code

 

posted @ 2014-08-22 13:09  Wurq  阅读(156)  评论(0编辑  收藏  举报