本節內容主要對Python中if和for循環應用進行簡要的學習
水仙花數(Narcissistic number)也被稱為超完全數字不變數(pluperfect digital invariant, PPDI)、自戀數、自冪數、阿姆斯壯數或阿姆斯特朗數(Armstrong number),水仙花數是指一個 n 位數(n≥3 ),它的每個位上的數字的 n 次冪之和等於它本身(例如:1^3 + 5^3+ 3^3 = 153)。
定義:水仙花數只是自冪數的一種,嚴格來說3位數的3次冪數才稱為水仙花數。
附:其他位數的自冪數名字
一位自冪數:獨身數
兩位自冪數:沒有
三位自冪數:水仙花數
四位自冪數:四葉玫瑰數
五位自冪數:五角星數
六位自冪數:六合數
七位自冪數:北鬥七星數
八位自冪數:八仙數
九位自冪數:九九重陽數
十位自冪數:十全十美數
列印出所有的「水仙花數」 ,所謂「水仙花數」是指一個三位數,其各位數字立方和等於該數本身。例如:153 是一個「水仙花數」 ,因為 153=1 的三次方+5 的三次方 +3 的三次方。
Python代碼1如下:
max_num = int(input('請輸入最大範圍')) # 獲取小於指定數的阿姆斯特朗數
for num in range(0, max_num):
sum = 0
length = len(str(num))
temp = num
for i in range(length):
sum += (temp % 10) ** length
temp //= 10
if sum == num:
print(num)
Python輸出結果以及操作圖示如:
Python代碼2如下:
import math
for i in range(100,1000):
x = math.floor(i / 100) # 獲取百位上的數
y = math.floor((i - x * 100) / 10) # 獲取十位上的數
z = i - math.floor(i / 10) * 10 # 獲取個位上的數
if i == x ** 3 + y ** 3 + z ** 3:
print(i,end=", ")
Python代碼3如下:
l = [ ]
for i in range(100,1000):
m = int(i/100)
n = int(i%100/10)
p = i%100%10
if i == m*m*m+n*n*n+p*p*p:
print(i)
l.append(i)
print(l)
上述代碼已經全部測試,均有效,有什麼問題直接留言交流!
本文來源:代碼1來源百度百科,其他來源於網絡