Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การหา Factorial ใน Python: 3 วิธี (Loop, Recursion, math.factorial)

Factorial (แฟกทอเรียล) ของจำนวนเต็มบวก n (เขียนว่า n!) คือ ผลคูณของจำนวนเต็มบวกทุกตัวตั้งแต่ 1 ถึง n โดยที่ 0! = 1

วิธีที่ 1: ใช้ For Loop (Iterative)

def factorial_iterative(n):
    """คำนวณ Factorial ด้วย Loop"""
    if n < 0:
        raise ValueError("Factorial ไม่ได้นิยามสำหรับจำนวนติดลบ")
    if n == 0 or n == 1:
        return 1
    
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# ทดสอบ
for i in range(0, 11):
    print(f"{i}! = {factorial_iterative(i)}")

วิธีที่ 2: ใช้ Recursion (Recursive)

def factorial_recursive(n):
    """คำนวณ Factorial ด้วย Recursion"""
    if n < 0:
        raise ValueError("Factorial ไม่ได้นิยามสำหรับจำนวนติดลบ")
    if n == 0 or n == 1:
        return 1
    return n * factorial_recursive(n - 1)

# ทดสอบ
print(factorial_recursive(5))   # 120
print(factorial_recursive(0))   # 1

# ⚠️ ข้อจำกัด: Recursion Depth
import sys
print(sys.getrecursionlimit())  # Default 1000
# factorial_recursive(1000) -> RecursionError

วิธีที่ 3: ใช้ math.factorial() (Built-in - แนะนำ)

import math

# ใช้ Built-in (เร็วที่สุด, จัดการ Edge Cases, รองรับ Big Integers)
print(math.factorial(5))    # 120
print(math.factorial(0))    # 1
print(math.factorial(20))   # 2432902008176640000
print(math.factorial(100))  # จำนวนใหญ่มาก (Python รองรับ Big Int อัตโนมัติ)

# Error Handling
try:
    math.factorial(-1)   # ValueError
except ValueError as e:
    print(f"Error: {e}")

try:
    math.factorial(3.5)  # ValueError (ต้องเป็น Integer)
except ValueError as e:
    print(f"Error: {e}")

การเปรียบเทียบประสิทธิภาพ

import timeit
import math

n = 100

# Iterative
t1 = timeit.timeit(lambda: factorial_iterative(n), number=10000)
print(f"Iterative: {t1:.4f}s")

# Recursive
t2 = timeit.timeit(lambda: factorial_recursive(n), number=10000)
print(f"Recursive: {t2:.4f}s")

# math.factorial
t3 = timeit.timeit(lambda: math.factorial(n), number=10000)
print(f"math.factorial: {t3:.4f}s")

ผลลัพธ์ทั่วไป

Iterative:     0.0120s
Recursive:     0.0180s
math.factorial: 0.0015s  (เร็วที่สุด 10x)

การประยุกต์ใช้: Permutations และ Combinations

import math

def permutations(n, r):
    """nPr = n! / (n-r)!"""
    return math.factorial(n) // math.factorial(n - r)

def combinations(n, r):
    """nCr = n! / (r! * (n-r)!)"""
    return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

print(f"5P3 = {permutations(5, 3)}")  # 60
print(f"5C3 = {combinations(5, 3)}")  # 10

Gamma Function (ขยาย Factorial ไปสู่ Real/Complex Numbers)

import math

# Gamma(n) = (n-1)! สำหรับ Positive Integer
print(math.gamma(6))    # 120.0 = 5!
print(math.gamma(5.5))  # 52.342777... (Factorial ของ 4.5)

# Relation: n! = Gamma(n+1)
for i in range(1, 6):
    print(f"{i}! = {math.factorial(i)} = Gamma({i+1}) = {math.gamma(i+1)}")

สรุป

วิธีPerformanceReadabilityLimitationsแนะนำ
For LoopปานกลางดีManual Implementationการเรียนรู้ Algorithm
Recursionช้า, Stack Overflow RiskElegantRecursion Limit (~1000)การสอน Recursion
math.factorial()เร็วที่สุด (C Implementation)ดีที่สุดไม่มี (รองรับ Big Int)Production Code ✅