阶乘的0
时间限制: 3000ms
内存限制: 128000KB
64位整型: Java 类名:
题目描述
计算n!的十进制表示最后有多少个0
输入
第一行输入一个整数N表示测试数据的组数(1<=N<=100)
每组测试数据占一行,都只有一个整数M(0<=M<=10000000)
每组测试数据占一行,都只有一个整数M(0<=M<=10000000)
输出
输出M的阶乘的十进制表示中最后0的个数
比如5!=120则最后的0的个数为1
比如5!=120则最后的0的个数为1
样例输入
6 3 60 100 1024 23456 8735373
样例输出
0 14 24 253 5861 2183837
来源
思路:只有是乘以5的倍数的数,才可能在结尾处有零的。只要是偶数相乘就可以,不需要考虑偶数的个数,所以只要计算5的个数就可以了,因此把每个数分解因子,统计5的因子个数。
#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int k, n,m=0,i;
scanf("%d",&n);
for(i=5;i<=n;i+=5)
{ k=i;
while(k%5==0)
{
m++;
k=k/5;
}
}
printf("%d\n",m);
}
return 0 ;
}
上面的那个算法在51nod上超时,在上面的基础上,奉上一个改进的代码,也很好理解。
#include <stdio.h>
#include <string.h>
#include <math.h>
#define maxn 1000000000
int k,n;
int main()
{
int n;
scanf("%d",&n);
long long int i,cont=0,j;
for( i=5,j=1;i<=n;i+=5,j++)
{
if(j%5==0)
{
int term=j;
while(term%5==0)
{
term=term/5;
cont++;
}
}
}
cont+=j-1;
printf("%d\n",cont);
return 0;
}