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

วิธาสร้าง Strong Numbers ด้วย Python

Strong Number คือเลขที่เท่ากับผลรวมแฟกทอเรียลของหลักตัวเอง เช่น 145 เป็น Strong number สร้างฟังก์ชันคำนวณแฟกทอเรียลก่อน

def fact(num):
    def factorial(n):
        num = 1
        while n >= 1:
            num = num * n
            n = n - 1
        return num

พิมพ์ Strong numbers ได้ด้วยโค้ดนี้

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num

def print_strong_nums(start, end):
    for i in range(start, end + 1):
        digits = list(map(int, str(i)))
        total = 0
        for d in digits:
            total += factorial(d)
        if total == i:
            print(i)

print_strong_nums(1, 380)

ผลลัพธ์:

1 2 145