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

ตรวจสอบว่าผลรวมหลักเลขตำแหน่งคี่ หาร k ลงตัวหรือไม่ด้วย Python

โจทย์: กำหนดเลข n และ k ตรวจสอบว่าผลรวมหลักเลขตำแหน่งคี่ (นับจากขวา: Units=1, Tens=2, ...) หาร k ลงตัวหรือไม่

ตัวอย่าง

n = 2416, k = 5 → หลักคี่: 6 (pos1), 4 (pos3) → Sum=10 → 10%5=0 → True

อัลกอริทึม

  1. total = 0, pos = 1
  2. While n > 0:
    • ถ้า pos คี่ → total += n % 10
    • n //= 10, pos += 1
  3. ตรวจสอบ total % k == 0

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

def solve(n, k):
    total = 0
    pos = 1
    while n > 0:
        if pos % 2 == 1:
            total += n % 10
        n = n // 10
        pos += 1
    if total % k == 0:
        return True
    return False

n = 2416
k = 5
print(solve(n, k))

Input / Output

Input: 2416, 5
Output: True