Python Armstrong Number Checker
Verify if a number is an Armstrong (narcissistic) number where the sum of its own digits raised to the power of the number of digits equals the number itself.
How it Works
An Armstrong number (also known as a narcissistic or pluperfect digital invariant number) is an n-digit number that is equal to the sum of the nth powers of its digits.
For example, 153 is a 3-digit Armstrong number because 1^3 + 5^3 + 3^3 = 153. Similarly, 9474 is a 4-digit Armstrong number because 9^4 + 4^4 + 7^4 + 4^4 = 9474.
We implement this in Python by converting the integer to a string to easily count the number of digits and iterate through each digit.
Source Code
Check a series of numbers to determine if they meet the mathematical criteria for Armstrong numbers.
def is_armstrong(num):
num_str = str(num)
n = len(num_str)
digit_sum = sum(int(digit) ** n for digit in num_str)
return digit_sum == num
test_nums = [153, 370, 9474, 123]
for val in test_nums:
result = "Armstrong" if is_armstrong(val) else "Not Armstrong"
print(f"{val:4d} -> {result}") 153 -> Armstrong
370 -> Armstrong
9474 -> Armstrong
123 -> Not ArmstrongReal-world Applications
- Number theory research and logic exercises
- Classroom math programming assignments
- Recreational programming
Frequently Asked Questions
Are all single-digit numbers Armstrong numbers?
Yes. Any single digit raised to the power of 1 is equal to itself (e.g., 5^1 = 5).
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Generate Random Numbers in Python
Learn how to generate random numbers in Python. Compare randrange, randint, and uniform float generation with seeding control.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.