Latest web development tutorials

Python Armstrong Number

Document Object Reference Examples Python3

If an n-bit positive integer equal to the digits of the n-th power sum, the number is called Armstrong number. For example, 1 ^ 3 ^ 3 + 3 + 5 = 153 ^ 3.

Armstrong number less than 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

The following code is used to detect whether the user-entered digits Armstrong Number:

# Filename : test.py
# author by : www.w3big.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,"不是阿姆斯特朗数")

Execute the above code output results:

$ python3 test.py 
请输入一个数字: 345
345 不是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 153
153 是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 1634
1634 是阿姆斯特朗数

Gets the number of Armstrong specified period

# Filename :test.py
# author by : www.w3big.com

# 获取用户输入数字
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)

Execute the above code output results:

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

The above example we output a number Armstrong 1-10000 between.

Document Object Reference Examples Python3