Description
The expression N!, read as "N factorial," denotes the product of the first N positive integers, where N is nonnegative. So, for example,
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.
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
解题思路:
本题不宜采用求出N的阶乘后再求最低位不为零的数字,这种方法理论可行,实际上不可行,该方法既费时,又繁琐,数太大后无法储存,超出long long型。本题只要求求出最低位不为零的数字,因此只需取后几位数不断相乘即可,注意,如果最低位是零,那么再与其它数相乘依然是零,没有必要,因此最低位出现零,就将其去除,接着往下乘。
代码如下:
#include<stdio.h>
int main()
{
int i,j,N,m;
while(scanf("%d",&N)!=EOF)
{
m=N;//记录N的值,对n操作即是对m操作,最终输出时需要N的值
//利用for循环,计算N的阶乘
for(i=N-1;i>=1;i--)
{
m=m*i;//计算N的阶乘
//最低位出现0就去除
if(m%10==0)
{
m=m/10;
}
//只留下四个非零的最低位数继续计算
m=m%10000;
}
//最终计算出的结果的最低位就是所求数字
m=m%10;
printf("%5d -> %d\n",N,m);
}
return 0;
}