A过去后看了一下别人的解法,发现除了打表还有一种数论的方法。
分析一下阶乘后面的0是怎么出现的呢,当然是2乘5得到的。
我们将1~N先放在一个数组里面。
从数组第一个元素开始,先统计一下N!中因子为5的个数记为count,将其除去,然后再除去count个2。这样一来的话把所有元素乘起来后就不会出现10的倍数了。
当然并不是真正的乘起来,那样的话肯定是要溢出的,因为只关心最后一位数,所以每次乘完后求10的余数即可。
我的做法是打表,因为题目里给了N <= 10000的条件限制,所以可以把1~10000的阶乘的第一个非0的数先算出来放到数组里,然后求哪个输出哪个即可。
| Just the Facts |
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 ( ). 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
Miguel A. Revilla
1998-03-10 打表代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 int a[40000], b[10000 + 10]; 7 int f(int n); 8 9 int main(void) 10 { 11 freopen("asdasd.txt", "w", stdout); 12 a[0] = 1; 13 b[0] = b[1] = 1; 14 int i; 15 for(i = 2; i <= 10000; ++i) 16 { //乘以i 17 int k = i, c = 0; 18 while(k % 10 == 0) 19 k /= 10; 20 for(int j = 0; j < 40000; ++j) 21 { 22 int s = a[j] * k + c; 23 a[j] = s % 10; 24 c = s / 10; 25 } 26 b[i] = f(i); 27 } 28 for(i = 0; i <= 10000; ++i) 29 { 30 printf("%d,", b[i]); 31 if(i % 20 == 0) 32 printf("\n"); 33 } 34 35 return 0; 36 } 37 //求n!的第一个非0的数 38 int f(int n) 39 { 40 int i; 41 for(i = 0; i <= 40000; ++i) 42 if(a[i] != 0) 43 break; 44 return a[i]; 45 }