Problem statement: Find the number of trailing zeros in the decimal representation of N!.
You can find the actual problem statement here.
Here is what I tried :
#include <stdio.h>
int fct(int n);
int main(void)
{
int n,t;
scanf("%d",&t);
while(t-- > 0)
{
scanf("%d",&n);
printf("%d\n",fct(n)-n);
}
return 0;
}
int fct(int n)
{
static int s=0;
if(n<5)
return s+n;
else
{
s=fct(n/5);
s=s+n;
return s;
}
}
Any help would be appreciated.
P.S. My above recursive function does'nt return the actual answer and I was not able write a function that returns the actual answer(number of trailing zeroes). Hence I needed some help in doing so.
I think the program I posted below does that.
That should be "static int fct(int n)". The static represents that the name fct has file scope, rather than the scope of the entire linked project.
Don't mix persistent and functional behavior, even though C lets you. I suggest:
because it is a lot less confusing.
Why are you calculating Z(n) + n? Why not just calculate Z(n) directly? Are you trying to make this hard on yourself?
Don't name things fct. The english language has a lot of words in it. Learn to use them. Also, this function should be tagged as static to indicate that it has file scope rather than global scope.
Don't make local variables static. It puts them in "static memory" rather than making a new variable on the stack, making your function only work once, then fail forever more.
Again, why this misery of trying to calculate Z(n) + n rather than just Z(n) ?
It appears what you are trying to implement tail recursion. Tail recursion is a type of recursion where the return value is passed on the stack as a parameter. You are avoiding the stack by using a static variable, which breaks everything, but effecting you are creating a helper function like:
Trying to learn tail recursion before you can do regular recursion is a bad idea. Just write it like:
That said, since you are trying to implement it recursively, rather than as effeciently as possible, try to implement this:
Try to implement that by starting by checking n, then recurring on Z(n - 1).