Python Program to Check an Armstrong Number
Beginner Numbers
Checks whether a number equals the sum of its digits, each raised to the power of how many digits it has.
An Armstrong number (also called a narcissistic number) equals the sum of its own digits, each raised to the power of how many digits it has. 153 is one: it has 3 digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153. It's a favourite school program because it practises loops, digits and powers in a few lines.
Program
def is_armstrong(number):
"""True if number is an Armstrong number."""
digits = str(number)
power = len(digits)
total = 0
for digit in digits:
total += int(digit) ** power
return total == number
print("153:", is_armstrong(153))
print("123:", is_armstrong(123))
Open in the editor Download armstrong_number.py
Output
153: True
123: False
How it works
Step through the program line by line: each step below shows up as its line runs.
-
str(number)turns the number into text, so the loop can go through its digits one by one. -
len()of that text is how many digits the number has: the power each digit is raised to. - The loop adds up each digit raised to that power.
int(digit)turns the digit back into a number first, as"5" ** 3would be an error. - The number is an Armstrong number when that total equals the number itself.
- The program checks 153, which is one, and 123, which isn't: 1³ + 2³ + 3³ is only 36.
The power changes with the number of digits: 9474 has 4 digits, so each digit is raised to the 4th power (9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474).
Other ways to write it
With sum() and a generator expression
The loop fits in one line with sum() and a generator expression:
def is_armstrong(number):
digits = str(number)
return sum(int(digit) ** len(digits) for digit in digits) == number
print(is_armstrong(153), is_armstrong(154))Without turning the number into text
Some exams ask for this version: % 10 gives the last digit and // 10 removes it.
def is_armstrong(number):
# Count the digits
count, n = 0, number
while n > 0:
count += 1
n //= 10
# Add up each digit to the power of the count
total, n = 0, number
while n > 0:
total += (n % 10) ** count
n //= 10
return total == number
print(is_armstrong(370), is_armstrong(371), is_armstrong(372))Try it yourself
- Check 370, 371, 407 and 9474, which are Armstrong numbers, and a few that aren't.
- Print every Armstrong number below 1000 with a loop or a list comprehension. There are 13, counting 1 to 9.
- Find every Armstrong number below 100,000: there are three with 4 digits and three with 5.
- Print the working next to the result, as
153 = 1^3 + 5^3 + 3^3.