Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to find the factorial of a number without recursion
When it is required to find the factorial of a number without using recursion, the while loop can be used. The factorial of a number n is the product of all positive integers from 1 to n, denoted as n!.
What is Factorial?
Factorial of a number n (written as n!) is defined as:
- n! = n × (n-1) × (n-2) × ... × 2 × 1
- 0! = 1 (by definition)
- Examples: 5! = 5 × 4 × 3 × 2 × 1 = 120
Using While Loop
We can calculate factorial by multiplying numbers from n down to 1 ?
# Method 1: Multiplying from n down to 1
num = 7
factorial = 1
while num > 0:
factorial = factorial * num
num = num - 1
print(f"The factorial of 7 is: {factorial}")
The factorial of 7 is: 5040
Using For Loop (Alternative Approach)
We can also use a for loop with range() for a more concise solution ?
# Method 2: Using for loop
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is: {factorial}")
The factorial of 5 is: 120
Complete Program with Input
Here's a complete program that takes user input and handles edge cases ?
def factorial_iterative(n):
if n < 0:
return "Factorial is not defined for negative numbers"
factorial = 1
while n > 0:
factorial = factorial * n
n = n - 1
return factorial
# Test with different numbers
numbers = [0, 1, 5, 7]
for num in numbers:
result = factorial_iterative(num)
print(f"Factorial of {num} is: {result}")
Factorial of 0 is: 1 Factorial of 1 is: 1 Factorial of 5 is: 120 Factorial of 7 is: 5040
How It Works
The algorithm follows these steps:
- Initialize: Set factorial = 1 and get the input number
- Loop: While the number is greater than 0
- Multiply: factorial = factorial × current number
- Decrement: Reduce the number by 1
- Repeat: Continue until number becomes 0
- Return: The final factorial value
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| While Loop | O(n) | O(1) | Good |
| For Loop | O(n) | O(1) | Better |
| Recursion | O(n) | O(n) | Elegant |
Conclusion
Using iterative approaches (while or for loop) to calculate factorial is memory-efficient with O(1) space complexity. The while loop method is straightforward and avoids the overhead of recursive function calls.
