Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the number of recursive calls made to calculate the factorial of n in Python

I want to write a recursive function named recursive_factorial(n) that takes a non-negative integer as a parameter and calculates the result of factorial(n). The function returns a tuple containing the result and the number of recursive calls made, in that order.

— The first function call does not count as a recursive call.

def recursive_factorial(n):
    if n == 0:
        return 1, 0
    else:
        value,step = recursive_factorial(n-1)
        return n * value, step + 1

Test and Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>> print(recursive_factorial(1))
(1, 0) --- Expected
(1, 1) --- Gotten

>> print(recursive_factorial(3))
(6, 2) --- Expected
(6, 3) --- Gotten

>> print(recursive_factorial(8))
(40320, 7) --- Expected
(40320, 8) --- Gotten

>Solution :

If you want to count the number of recursive calls, your expectations are wrong since you’re not counting the call with n=1.

To show you that with an example, let’s immagine you call recursive_factorial(3). The stack of calls will be

  1. recursive_factorial(3)
  2. recursive_factorial(2)
  3. recursive_factorial(1)
  4. recursive_factorial(0)

Since you said you’re not counting the case with n=0, the expected count should be 3, not 2 as you would have expected

If you want the counter to match the current expectation you have to add another base case

def recursive_factorial(n):
if n == 0 or n ==1:
    return 1, 0
else:
    value,step = recursive_factorial(n-1)
    return n * value, step + 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading