Python實(shí)現(xiàn)“韓信點(diǎn)兵”

題目:

相傳韓信才智過人,從不直接清點(diǎn)自己軍隊(duì)的人數(shù),只要讓士兵先后以三人一排、五人一排、七人一排地變換隊(duì)形,而他沒次只掠一眼隊(duì)伍的排尾就知道總?cè)藬?shù)了。輸入包含多組數(shù)據(jù),每組數(shù)據(jù)包含3個(gè)非負(fù)整數(shù)a,b,c,表示每種隊(duì)形排尾的人數(shù)(a<3,b<5,c<7),輸出總?cè)藬?shù)的最小值(或報(bào)告無解)。已知總?cè)藬?shù)不小于10,不超過100。輸入到文件結(jié)束為止

樣例輸入
2 1 6
2 1 3

樣例輸出
Case 1: 41
Case 2: No answer

思路:

設(shè)總?cè)藬?shù)為n,則當(dāng)三人一排時(shí)有 n%3 == a, 當(dāng)五人一排時(shí)有 n%5 == b,當(dāng)七人一排時(shí)有 n%7 == c,因此求出同時(shí)滿足上述三個(gè)條件的n即可

代碼:

import sys

count = 0
while True:
    num = input()
    if num != "":
        num = num.split()
        a = num[0]
        b = num[1]
        c = num[2]
        count += 1
        if len(num) == 3 and int(a) < 3 and int(b) < 5 and int(c) < 7:
            flag = True
            for i in range(10, 101):
                if i % 3 == int(a) and i % 5 == int(b) and i % 7 == int(c):
                    print("Case {0}: {1}".format(count, i))
                    flag = False
                    break

            if flag:
                print("Case {0}: No answer".format(count))

    else:
        sys.exit()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容