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

โปรแกรม Python หา Factorial (แฟกทอเรียล) ของเลข

โจทย์: หา Factorial ของ n (n! = n × (n-1) × ... × 1) มี 2 วิธี

วิธี 1: Recursive

def factorial(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print("Factorial of", 6, "is", factorial(6))

ผลลัพธ์

Factorial of 6 is 720

โปรแกรม Python หา Factorial (แฟกทอเรียล) ของเลข

วิธี 2: Iterative

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

print("Factorial of", 6, "is", factorial(6))

ผลลัพธ์

Factorial of 6 is 720

โปรแกรม Python หา Factorial (แฟกทอเรียล) ของเลข

สรุป

เรียนรู้ 2 วิธีคำนวณ Factorial ใน Python: Recursive และ Iterative (Loop)