1

Python version 2.7.6

I wrote an iterative function that computes the number of trailing zeros expected with a particular factorial. I then tried to rewrite it as a recursive function. This is the recursive result:

def f_FactorialTailZeros(v_Num, v_Result = 0):
    if v_Num < 5:
        return v_Num
    v_Result = v_Result + f_FactorialTailZeros(v_Num // 5, v_Num // 5)
    return v_Result

print(f_FactorialTailZeros(30)) ## 7
print(f_FactorialTailZeros(70)) ## 16

It works, but, for the sake of learning, is there a better way?

3
  • Do you mean to return 0 for values less than 5? Commented Jun 23, 2015 at 7:08
  • 1
    I don't see any problem at all with the way you have defined the recursive function. Offtopic: the prefix notation is something to avoid nowadays. Commented Jun 23, 2015 at 7:09
  • // , Ikaros, can you provide any further reading on that? Commented Jun 27, 2015 at 21:00

2 Answers 2

3

Based on your code:

def f_FactorialTailZeros(v_Num):
    if v_Num < 5:
        return 0
    return v_Num // 5 + f_FactorialTailZeros(v_Num // 5)
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that's the ticket. And I see where I went off track as well, which is the most important thing. Thanks.
Yes, I think this is optimal. The beauty of recursion lies in the fact that you shouldn't need to keep track of state. Plus, passing in duplicate parameters to a function should also raise a red flag. Good job OP for coming up with the recursive solution though! It's pretty neat and not immediately obvious until you see it.
2

Yes, you can do it with recursive function have a look at following code and FYI read this

def recursive_trailingZeroes(A):
    if A==0:
        return 0
    return (A//5)+recursive_trailingZeroes(A//5)

2 Comments

SO already finished the iterative method he wants to do it in recursive way
Thanks, however, I have an iterative version that works. I wanted to know if there were a better recursive version than the one that I wrote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.