Python Tutorial (33) - Example: Armstrong Number

Time: Column:Python views:237

Armstrong Numbers in Python

An Armstrong number (or Narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 13+53+33=1531^3 + 5^3 + 3^3 = 153.

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

The following code checks whether a user-input number is an Armstrong number:

Example

# Filename: test.py
# Author: www.runoob.com

# Python code to check if the user-input number is an Armstrong number

# Get user input
num = int(input("Enter a number: "))

# Initialize sum
sum = 0
# Number of digits
n = len(str(num))

# Check if it is an Armstrong number
temp = num
while temp > 0:
    digit = temp % 10
    sum += digit ** n
    temp //= 10

# Output result
if num == sum:
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")

Example Output:

$ python3 test.py 
Enter a number: 345
345 is not an Armstrong number

$ python3 test.py 
Enter a number: 153
153 is an Armstrong number

$ python3 test.py 
Enter a number: 1634
1634 is an Armstrong number

To find Armstrong numbers within a specific range, you can use the following code:

Example

# Filename: test.py
# Author: www.runoob.com

# Get user input
lower = int(input("Enter the minimum value: "))
upper = int(input("Enter the maximum value: "))

for num in range(lower, upper + 1):
    # Initialize sum
    sum = 0
    # Number of digits
    n = len(str(num))

    # Check if it is an Armstrong number
    temp = num
    while temp > 0:
        digit = temp % 10
        sum += digit ** n
        temp //= 10

    if num == sum:
        print(num)

Example Output:

Enter the minimum value: 1
Enter the maximum value: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

In this example, the program prints Armstrong numbers between 1 and 10000.