Python Armstrong Number

Document 对象参考手册Python3 Examples

If annn-digit positive integer is equal to its digits'nsum of powers, then the number is called an Armstrong number.1^3 + 5^3 + 3^3 = 153。

Armstrong numbers within 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

The following code is used to check whether the number entered by the user is an Armstrong number:

Example (Python 3.0+)

# Filename : test.py # author by : www.example.com # Python checks whether the number entered by the user is an Armstrong number # Get the number entered by the user num = int(input("Please enter a number:")) # Initialize variable sum sum = 0 # Exponent n = len(str(num)) # Check temp = num while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 # Output result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number")

Executing the above code produces the following output:

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

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

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

Get Armstrong numbers within a specified range

Example (Python 3.0+)

# Filename :test.py # author by : www.example.com # Get user input numbers lower = int(input("Minimum value:")) upper = int(input("Maximum value:")) for num in range(lower,upper + 1): # Initialize sum sum = 0 # Exponent n = len(str(num)) # Check temp = num while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 if num == sum: print(num)

Executing the above code produces the following output:

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

In the above example, we output the Armstrong numbers between 1 and 10000.

Document 对象参考手册Python3 Examples

Other extensions