Mandelbrotr Logo

Mandelbrotr

Created By: ATTAP

Makes beautiful fractals

Create 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 IS FREE TO TRY
  • NO SUBSCRIPTION TRAPS
  • JUST PAY FOR WHAT YOU USE
  • Claim Your Reward: Sign up and get 500 free credits which will enable you to try all ATTAP features.
  • Simple & Secure Signup:
    • Only a valid email address is required.
    • Your profile information will not be shared or transmitted without your express consent.
    • Unlock Full Access: Your account enables you to enjoy all ATTAP features, including:
      • Creating, sharing and storing your VIBES.
      • Securely archiving all your ATTAP queries.
      • Saving your Vibing history and more.
      • Gift credits to family, friends and colleagues.
Scroll Up Scroll Down
Copied URL into clipboard