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

Triangular Matchstick Number ใน Python

โจทย์: หาจำนวนไม้ขีดไฟ (Matchsticks) สำหรับพีระมิดสามเหลี่ยม X ชั้น

สูตรคณิตศาสตร์

ชั้นที่ i ต้องการ 3i ไม้ (สามเหลี่ยมด้าน i)
รวม = 3 × (1 + 2 + ... + X) = 3 × X(X+1)/2 = 3X(X+1)/2

ตัวอย่าง

X = 21 ชั้น
Matchsticks = 3 × 21 × 22 / 2 = 693

ตัวอย่างโค้ด Python

def matchstick_pyramid(floors):
    """คำนวณไม้ขีดไฟสำหรับพีระมิดสามเหลี่ยม"""
    return (3 * floors * (floors + 1)) // 2

# ทดสอบ
n = 21
result = matchstick_pyramid(n)
print(f"Floors: {n}, Matchsticks needed: {result}")
# Output: 693

ผลลัพธ์

693

การขยาย: แสดงโครงสร้าง

def print_pyramid_structure(floors):
    for i in range(1, floors + 1):
        triangles_in_row = i
        matchsticks_in_row = 3 * i
        print(f"Floor {i}: {triangles_in_row} triangles, {matchsticks_in_row} matchsticks")
    
    total = matchstick_pyramid(floors)
    print(f"Total: {total}")

print_pyramid_structure(5)
# Floor 1: 1 triangles, 3 matchsticks
# Floor 2: 2 triangles, 6 matchsticks
# Floor 3: 3 triangles, 9 matchsticks
# Floor 4: 4 triangles, 12 matchsticks
# Floor 5: 5 triangles, 15 matchsticks
# Total: 45

ความซับซ้อน: Time O(1), Space O(1) - คำนวณได้ทันทีจากสูตร