[英]Z function for factorial in C
I came across a question online - to find the Z function of the factorial of t nos (no of zeroes at the lsb end of the factorial) 我在网上碰到一个问题-查找t nos阶乘的Z函数(阶乘的lsb末尾为零)
#include<stdio.h>
int fact(int x)
{
if(x==1)
return 1;
else
return (x*fact(x-1));
}
int main()
{
int t,n,k,c;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
k=fact(n);
c=0;
while(k%10==0)
{
k/=10;
c++;
}
printf("%d\n",c);
}
return 0;
}
This is the program I made, but it's too slow. 这是我制作的程序,但是太慢了。 How can I do this faster?
我怎样才能更快地做到这一点?
Looking at your code I can think of two possible solutions at the first glance. 乍一看您的代码,我可以想到两种可能的解决方案。
Memoization technique can speed up the calculation significantly, though at the cost of usage of memory. 内存化技术可以大大加快计算速度,但会占用内存。 If I were you I'd do the memoization.
如果我是你,我会做备忘录。 I am very confident your code will run faster, since it is a simple factorial function (actually a classic example for memoization, like the Fibonacci numbers).
我非常有信心您的代码将运行得更快,因为它是一个简单的阶乘函数(实际上是记忆的经典示例,如斐波那契数字)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.