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 can I make my recursion program to output factorial of a number more efficient?

I have made a Program which outputs the factorial of a number by calling the function: factorial() which uses recursion to calculate and return the value. I have also included a loop to break the program when the User inputs the word "off". Please suggest any improvements

HERE IS THE CODE:

def factorial(base):
    if base == 0 or base == 1:      
        return 1                                  
    else:
        return base * factorial(base - 1)                            


while True:
   base: int = int(input("Enter a base number: "))
   Result = factorial(base)
   print(f"The factorial of {base} is: {Result}")
   offf: str = input("Enter 'off' to terminate calculations: ")
   if offf == "off":
    print("Calculations Terminated")
    break

HERE IS THE TERMINAL:
Output of my code

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

>Solution :

While recursive approach seems like a natural thing to do, sadly that is not very efficient, as each call requires a separate stack frame to be created. It also causes problems due to Python’s recursion depth limit, which means you this program will raise an exception for any base > 1000. Iterative approach (with loops) is around 2-3 times faster and avoids the recursion limit problems.

def factorial_iterative(base, acc = 1):
    acc = 1
    for i in range(1, base+1):
        acc *= i
    return acc
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