0

Factorial Python

How to calculate factorial using loop.when should we use iteration vs recursion? Is performance different

21st Mar 2025, 1:33 PM
AriYa
3 Answers
+ 2
D1M1TRIĐŻ , Don't give readymade code...let them try themselves... And Ariya try it by yourself and share your code link here if you face issues... Don't expect for readymade code
21st Mar 2025, 3:31 PM
Riya
Riya - avatar
0
def factorial_recursive(n): if n < 0: return "Factorial is not defined for negative numbers" elif n == 0 or n == 1: return 1 else: return n * factorial_recursive(n - 1) # Example usage print(factorial_recursive(5)) # Output: 120 here is a recursive aproach
21st Mar 2025, 2:41 PM
D1M1TRIĐŻ
D1M1TRIĐŻ - avatar
0
Ariya 👉 When to use Iteration or Recursion For simple algorithms where performance is not critical, either can be used. For more complex algorithms, sometimes iteration or recursion will be easier to read and follow the logic. Example - Recursion is often used for binary tree traversal. 👉 Performance Iteration (looping) will perform better than most forms of recursion. Tail-end recursion is the one form of recursion which typically has performance equal to iteration. So if you do use recursion, try for tail-end. https://www.geeksforgeeks.org/tail-recursion/ https://stackoverflow.com/questions/33923/what-is-tail-recursion
22nd Mar 2025, 4:09 AM
Shardis Wolfe