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

การคำนวณแฟกทอเรียลใน Python แบบเรียกซ้ำ

ภาพรวม

แฟกทอเรียล (Factorial) ของจำนวน n เขียนว่า n! = n × (n-1) × (n-2) × ... × 1 โดยที่ 0! = 1 บทความนี้แสดงการคำนวณแบบเรียกซ้ำ (Recursive) ซึ่งเข้าใจง่ายและสอดคล้องกับนิยามทางคณิตศาสตร์

ตัวอย่าง

อินพุต: 6

เอาต์พุต: 720 (เพราะ 6! = 6×5×4×3×2×1 = 720)

โค้ด Python

class Solution:
    def solve(self, n):
        if n <= 1:
            return 1
        return n * self.solve(n - 1)

ob = Solution()
print(ob.solve(6))

วิธีการอื่นๆ

1. วนลูป (Iterative) - ประหยัดหน่วยความจำ

def factorial_iterative(n):
    result = 1
    for i in range(2, n+1):
        result *= i
    return result

2. ใช้ math.factorial (Built-in)

import math
print(math.factorial(6))  # 720

3. ใช้ functools.reduce

from functools import reduce
def factorial_reduce(n):
    return reduce(lambda x, y: x*y, range(1, n+1), 1)

ข้อควรระวัง

  • Recursion depth limit ใน Python ค่าเริ่มต้น ~1000
  • สำหรับ n มาก ควรใช้วิธีวนลูปหรือ built-in
  • โจทย์กำหนด n ≤ 10 จึงใช้ recursion ได้ปลอดภัย

ผลลัพธ์

720