📘 Lesson · Lesson 75
Factorial Program
Factorial Program
Factorial Program in Python (Loop and Recursion)
The factorial of n (written n!) is the product of all numbers from 1 to n. Example: 5! = 120.
Python Program
Python
# Using a loop
n = 5
f = 1
for i in range(1, n + 1):
f *= i
print("Factorial:", f)
# Using recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print("Recursive:", factorial(5))Expected Output
Factorial: 120
Recursive: 120
How it Works
- Loop: multiply f by each number from 1 to n.
- Recursion: n! = n × (n-1)!, with base case 0! = 1.
Summary
- The factorial of n (written n!) is the product of all numbers from 1 to n. Example: 5! = 120.
Factorial Program in Python (Loop and Recursion)
n का factorial (n! लिखते हैं) 1 से n तक सभी संख्याओं का गुणनफल है। Example: 5! = 120।
Python Program
Python
# Using a loop
n = 5
f = 1
for i in range(1, n + 1):
f *= i
print("Factorial:", f)
# Using recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print("Recursive:", factorial(5))Expected Output
Factorial: 120
Recursive: 120
कैसे काम करता है
- Loop: f को 1 से n तक हर संख्या से गुणा करें।
- Recursion: n! = n × (n-1)!, base case 0! = 1।
सारांश
- n का factorial (n! लिखते हैं) 1 से n तक सभी संख्याओं का गुणनफल है। Example: 5! = 120।