天天看點

Python 阿姆斯特朗數

Python3 執行個體

如果一個n位正整數等于其各位數字的n次方之和,則稱該數為阿姆斯特朗數。

例如1^3 + 5^3 + 3^3 = 153。

1000以内的阿姆斯特朗數:

1, 2, 3, 4, 5, 6, 7, 8, 9,

153, 370, 371, 407。

以下代碼用于檢測使用者輸入的數字是否為阿姆斯特朗數:

執行個體(Python 3.0+)

# Filename : test.py

# author by : www.runoob.com

# Python 檢測使用者輸入的數字是否為阿姆斯特朗數

# 擷取使用者輸入的數字

num = int(input("請輸入一個數字: "))

# 初始化變量 sum

sum = 0

# 指數

n = len(str(num))

# 檢測

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** n

temp //= 10

# 輸出結果

if num == sum:

print(num,"是阿姆斯特朗數")

else:

print(num,"不是阿姆斯特朗數")

執行以上代碼輸出結果為:

$ python3 test.py 
請輸入一個數字: 345
345 不是阿姆斯特朗數

$ python3 test.py 
請輸入一個數字: 153
153 是阿姆斯特朗數

$ python3 test.py 
請輸入一個數字: 1634
1634 是阿姆斯特朗數
      

擷取指定期間内的阿姆斯特朗數

# Filename :test.py

# 擷取使用者輸入數字

lower = int(input("最小值: "))

upper = int(input("最大值: "))

for num in range(lower,upper + 1):

# 初始化 sum

sum = 0

# 指數

n = len(str(num))

# 檢測

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** n

temp //= 10

if num == sum:

print(num)

最小值: 1
最大值: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
      

以上執行個體中我們輸出了 1 到 10000 之間的阿姆斯特朗數。

Python3 執行個體