0

This is a function i made to count number of zeroes at the end of the factorial of a number b recursively. However i'm getting runtime error due to the used code.Pardon my naivety but any help in this would be appreciated.

int noz(int b)
{ 
    int c=0;
    int e = b;
    if(e < 5)
       return 0; 
    while(e > 0)
       c = c + (e/5) + noz(e/5);
            return c; 
}
4

2 回答 2

4

You are encountering "runtime error" because:

int c;
...
while(e > 0)
   c = c + (e/5) + noz(e/5);  // <-- HERE

you are using uninitialized local variable c, which produces undefined behavior.

You could zero-initialize this variable to prevent it happen:

int c = 0;

And also note that in case that argument of your function is greater or equal than 5, this function doesn't return anything (thanks to @Paul R for pointing this out) and another problem is that you have loop with the condition e > 0 but the loop doesn't change the value of e making it infinite loop.

Your function could look like this instead (I'm not sure what exactly is the desired logic here):

int noz(int b)
{ 
    int c = 0;
    if (b < 5)
       return 0; 
    else
       return c + (b/5) + noz(b/5);
}
于 2013-03-30T08:21:09.430 回答
0
//count n! tail zero
int noz(int n){
    int count;

    if(n < 5) return 0;
    count = n / 5;
    return count + noz(count);
}
于 2013-03-30T09:08:32.323 回答