Mandelbrotr Logo

Mandelbrotr

Created By: ATTAP

Makes beautiful fractals

Create Vibe Comment on Vibe

Generate Python code to calculate the factorial of a number using three different methods and demonstrate with examples

Edit Title

User:

Write python code to generate the factorial of a number. 

Copy Feb. 23, 2026, 1:43 p.m.

Mandelbrotr:

Here is the Python code to calculate the factorial of a number. The factorial of a non-negative integer \( n \) (denoted as \( n! \)) is the product of all positive integers less than or equal to \( n \).

### 1. Iterative Approach
This method uses a loop to multiply the numbers.

```python
def factorial_iterative(n):
    if n < 0:
        return "Factorial does not exist for negative numbers"
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# Example usage
number = 5
print(f"The factorial of {number} is {factorial_iterative(number)}")
```

### 2. Recursive Approach
This method calls the function within itself to calculate the result.

```python
def factorial_recursive(n):
    if n < 0:
        return "Factorial does not exist for negative numbers"
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial_recursive(n - 1)

# Example usage
number = 5
print(f"The factorial of {number} is {factorial_recursive(number)}")
```

### 3. Using the Built-in `math` Module
Python has a built-in library optimized for this calculation.

```python
import math

number = 5
print(f"The factorial of {number} is {math.factorial(number)}")
```

Would you like me to explain how these methods work in more detail, or do you need the code in a different programming language like C++ or Java?

Copy Feb. 23, 2026, 1:43 p.m.

  • ATTAP GIVES YOU 500 FREE CREDITS TO START
  • NO SUBSCRIPTIONS, JUST PAY FOR WHAT YOU USE
  • Simple & Secure Signup: Only a valid email address is required. We don't track or share anything without your express consent.
  • /
Scroll Up Scroll Down
Copied URL into clipboard