题意:求N!结果中最后一位不为0的数字。如5! = 120,那么结果中最后一位不为0的数字就是2
解题思路:
- 因为N <= 4220,所以在每一步中只需要保存最后四位就可以了。
- 初始化result = 1,遍历1~N,每次用result * i,用result保存得到的结果的后四位不为0的数字。
- 取最后得到结果result的最后一位即可
代码:
/*
ID: zc.rene1
LANG: C
PROG: fact4
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
FILE *fin, *fout;
int result;
int N, i;
fin = fopen("fact4.in", "r");
fout = fopen("fact4.out", "w");
/*get input*/
fscanf(fin, "%d", &N);
/*begin DP*/
result = 1;
for (i=1; i<=N; i++)
{
result *= i;
while (result % 10 == 0)
{
result /= 10;
}
result %= 10000;
}
/*print result*/
fprintf(fout, "%d\n", result % 10);
return 0;
}