计算1000!末尾含有多少个0
开始,小瞧这个上机作业了,就单纯循环,然后判断末尾是否为零(好傻一猿) 还觉得自己十分机智的用了long long型。。。。。。 错误代码如下:
#include<stdio.h>
int main()
{
long long x
=1,n
, i
= 0;
for (n
= 1000; n
>=1; n
--)
{
x
*= n
;
while (x
% 10 == 0)
{
i
++;
x
/= 10;
}
}
printf("%lld", i
);
return 0;
}
搜了一下1000!的阶乘就蒙了,这么长long long都hold不住。真么办? 这时候,我们要想起mod,可以用来限制范围 末尾只要为0就不会改变,而且考虑乘后可为零的,只有后四位(三位也可以,这个地方我的逻辑不是很清晰) 所以就给数mod1000 正确代码如下
#include<stdio.h>
int main()
{
int x
=1,n
, i
= 0;
for (n
=1; n
<=1000; n
++)
{
x
*= n
;
while (x
% 10 == 0)
{
i
++;
x
/= 10;
}
x
%= 1000;
}
printf("%d", i
);
return 0;
}
初学,见谅 有错误欢迎指正