###### tags: `Python` # 第六堂課練習-題目練習 ## 練習一 382 - Perfection :::success 題目:382 - Perfection 1994年"數論(Number Theory)"一篇文章的作者,同時也是微軟(Microsoft)工程師的Encarta指出: 「假設 a, b, c 為三整數,且 a = bc 成立, a 被稱為 b 或 c 的倍數,而 b 或 c 被稱為 a 的除數或 因數。假設 c 不為正1或負1,則 b 可被稱為 "a的洽當因數(proper divisor of a) "。包含零的偶數為 2的倍數,例如:-4, 0, 2, 10...等,奇數為非偶數的整數,例如:-5, 1, 3, 9...等。一個 "完全數 (perfect number)" 為一正整數,它等於它的所有正的洽當因數(proper divisor)的和,例如6即為完 全數,它等於 1 + 2 + 3,而28 = 1 + 2 + 4 + 7 + 14 亦為完全數。一正整數若非完全數,則稱它 為"缺陷數(deficient)"或 "充裕數(abundant)" ,端看該數的所有正的洽當因數的和是否小於或大於 該數本身。因此, 9 的洽當因數為 1, 3,故9為"缺陷數",12為 "充裕數" 因為它的洽當因數等於 1, 2, 3, 4, 6」 ::: ```python= n=int(input('PERFECTION OUTPUT:')) while n >0 or n<0: #while迴圈 使用者輸入的數不為0會重複執行; 為0則跳出迴圈 x=0 #總和計算 for i in range (1,n): #從1~n 開始遞增+1 找因數 (從1到n-1停止) if n%i==0: #判斷 n如果被i整除 餘數為0, 則判斷為因數 x=x+i # 另一個寫法x+=i <<<< 將判斷為因數的數加總起來 if x == n: #總和 等於 使用者輸入的數 為完美數PERFECT print("PERFECT") elif x>n: #總和 大於 使用者輸入的數 為充裕數ABUNDANT print("ABUNDANT") else: #其他>>> 總和 小於 使用者輸入的數 為缺陷數DEFICIENT print("DEFICIENT") n=int(input('')) print("END OF OUTPUT") ``` :::spoiler 輸出結果 PERFECTION OUTPUT 15 DEFICIENT 28 PERFECT 6 PERFECT 56 ABUNDANT 60000 ABUNDANT 22 DEFICIENT 496 PERFECT END OF OUTPUT ::: ## 練習二 10783-Odd Sum :::success 題目: 10783 Odd Sum Given a range [a; b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3; 9] is 3 + 5 + 7 + 9 = 24. (只加總奇數) <font color="red">Sample Input </font> 2 1 5 3 5 <font color="red">Sample Output</font> Case 1: 9 Case 2: 8 ::: ```python= time=int(input('case times:')) #讓使用者輸入要做case的次數 for j in range(time): #用for迴圈去依照 使用者case的次數去執行(從0開始) x = int(input('Start:')) #讓使用者輸入開始的數 y = int(input('End:')) #讓使用者輸入停止的數 z = 0 #奇數加總 for i in range (x,y+1): #for迴圈判斷從 使用者輸入開始~停止的數 if(i % 2 == 1): #如果 除2餘數為1 即為奇數 z+=i #奇數 做加總 print('Case %d:%d'%(j+1,z)) #輸出Case 的加總結果 ``` :::spoiler 執行結果 case times:2 Start:1 End:5 Case 1:9 Start:3 End:5 Case 2:8 :::