Table of Contents
- What is an Armstrong Number? Understanding the Concept
- Why Learn Armstrong Numbers in Python?
- How to Check if a Number is an Armstrong Number in Python?
- Python Program to Find Armstrong Numbers in a Range
- List of Armstrong Numbers by Number of Digits
- Advanced Armstrong Number Programs
- Common Errors and How to Fix Them
- Practice Exercises and Challenges
- Real-World Applications and Interview Questions
- Complete Code Example (Copy-Paste Ready)
- Armstrong numbers: common questions
- Final Thoughts
An Armstrong number (also called a narcissistic number) is a number equal to the sum of its own digits, each raised to the power of the number of digits. 153 is one, because it has 3 digits and 13 + 53 + 33 = 1 + 125 + 27 = 153. So is 9474: 94 + 44 + 74 + 44 = 9474.
There are no 2-digit Armstrong numbers. The 3-digit ones are 153, 370, 371, 407; the 4-digit ones 1634, 8208, 9474; the 5-digit ones 54748, 92727, 93084; and the only 6-digit one is 548834. The list is finite: the On-Line Encyclopedia of Integer Sequences counts 89 of them including 0, and the largest has 39 digits.
Below: the definition worked through, the full list up to 7 digits with the program that finds it, three ways to check a number in Python, and the questions students ask most.
What is an Armstrong Number? Understanding the Concept
An Armstrong number (also called a narcissistic number or pluperfect digital invariant) is a number that equals the sum of its own digits, each raised to the power of the total number of digits.
Mathematical definition:
If a number has n digits, it's an Armstrong number when the sum of each digit raised to the power n equals the original number.
Simple examples to understand:
153 is an Armstrong number:
- Number of digits: 3
- Calculation: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
- Result: 153 = 153 ✓
9474 is an Armstrong number:
- Number of digits: 4
- Calculation: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474
- Result: 9474 = 9474 ✓
123 is NOT an Armstrong number:
- Number of digits: 3
- Calculation: 1³ + 2³ + 3³ = 1 + 8 + 27 = 36
- Result: 123 ≠ 36 ✗
Important note: every single-digit number from 0 to 9 is an Armstrong number, because a digit raised to the power 1 is itself: 51 = 5. Here is the same check in Python, showing the working for each number:
def is_armstrong(number):
digits = str(number)
power = len(digits)
return sum(int(d) ** power for d in digits) == number
for number in [153, 9474, 123]:
digits = str(number)
power = len(digits)
working = " + ".join(f"{d}^{power}" for d in digits)
total = sum(int(d) ** power for d in digits)
print(f"{number}: {working} = {total} ->", "Armstrong" if is_armstrong(number) else "not Armstrong")
153: 1^3 + 5^3 + 3^3 = 153 -> Armstrong
9474: 9^4 + 4^4 + 7^4 + 4^4 = 9474 -> Armstrong
123: 1^3 + 2^3 + 3^3 = 36 -> not Armstrong
Why Learn Armstrong Numbers in Python?
Working with Armstrong numbers provides excellent practice for fundamental Python concepts that every programmer needs.
Skills you'll develop:
- Loop mastery: Both while and for loops in practical scenarios
- Mathematical operations: Power calculations, modulo arithmetic, integer division
- Type conversions: Switching between strings and integers effectively
- Conditional logic: Using if-else statements for decision making
- Algorithm design: Breaking complex problems into step-by-step solutions
Practical benefits:
Armstrong number programs appear frequently in coding interviews, school assignments, and competitive programming. They test your ability to manipulate numbers, think logically, and write clean code.
The techniques you learn here, digit extraction, iterative checking, and mathematical validation, apply to countless other programming challenges.
How to Check if a Number is an Armstrong Number in Python?
Let's explore three different methods to check Armstrong numbers, each with its own advantages.
Method 1: Using While Loop (Traditional Approach)
This method extracts digits using mathematical operations, the classic algorithm approach.
def is_armstrong_while(number):
# Store original number
original = number
sum_of_powers = 0
# Count number of digits
num_digits = len(str(number))
# Extract digits and calculate sum
while number > 0:
digit = number % 10 # Get last digit
sum_of_powers += digit ** num_digits
number = number // 10 # Remove last digit
# Check if sum equals original number
return sum_of_powers == original
# Test the function
print(is_armstrong_while(153)) # True
print(is_armstrong_while(123)) # False
How it works:
- Store the original number for comparison
- Count digits by converting to string temporarily
- Extract each digit using modulo (%) to get the last digit
- Add digit raised to power to running sum
- Remove last digit using integer division (//)
- Compare final sum with original number
Method 2: Using String Conversion (Simpler Approach)
This method is more readable and easier for beginners to understand.
def is_armstrong_string(number):
# Convert to string to easily access each digit
digits = str(number)
num_digits = len(digits)
# Calculate sum of each digit raised to power
sum_of_powers = sum(int(digit) ** num_digits for digit in digits)
return sum_of_powers == number
# Test the function
print(is_armstrong_string(370)) # True
print(is_armstrong_string(400)) # False
Advantages:
- More concise and readable code
- Uses Python's string iteration naturally
- List comprehension makes it elegant
- Fewer variables to track
When to use: Great for learning and quick implementations. The while loop method is better for understanding the mathematical approach.
Method 3: Complete Program with User Input
Here's a practical program users can interact with.
def check_armstrong(number):
digits = str(number)
num_digits = len(digits)
sum_of_powers = sum(int(d) ** num_digits for d in digits)
return sum_of_powers == number
# Main program
num = int(input("Enter a number: "))
if check_armstrong(num):
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is not an Armstrong number.")
Python Program to Find Armstrong Numbers in a Range
Finding all Armstrong numbers within a specific range requires checking each number systematically.
def find_armstrong_in_range(start, end):
armstrong_numbers = []
for num in range(start, end + 1):
# Convert to string to get digits
digits = str(num)
num_digits = len(digits)
# Calculate sum of powers
sum_of_powers = sum(int(d) ** num_digits for d in digits)
# Check if Armstrong number
if sum_of_powers == num:
armstrong_numbers.append(num)
return armstrong_numbers
# Find all Armstrong numbers between 1 and 1000
result = find_armstrong_in_range(1, 1000)
print("Armstrong numbers between 1 and 1000:")
print(result)
Output:
Armstrong numbers between 1 and 1000:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
This program efficiently checks every number in the range and stores Armstrong numbers in a list for easy access.
List of Armstrong Numbers by Number of Digits
Armstrong numbers get rarer as numbers get longer. Here is every one with up to 7 digits, followed by the program that produced this list:
| Digits | How many | Armstrong numbers |
|---|---|---|
| 1 | 10 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 |
| 2 | 0 | none |
| 3 | 4 | 153, 370, 371, 407 |
| 4 | 3 | 1634, 8208, 9474 |
| 5 | 3 | 54748, 92727, 93084 |
| 6 | 1 | 548834 |
| 7 | 4 | 1741725, 4210818, 9800817, 9926315 |
The program tries each combination of digits once rather than every number, which is why it reaches 7 digits in about a second:
from itertools import combinations_with_replacement
# For n digits, only the multiset of digits matters for the sum, so try each
# multiset once instead of every number (about 11,000 checks instead of 10 million).
found = []
for n in range(1, 8):
for combo in combinations_with_replacement(range(10), n):
total = sum(d ** n for d in combo)
if len(str(total)) == n and sorted(int(c) for c in str(total)) == list(combo):
found.append(total)
for n in range(1, 8):
group = sorted(x for x in found if len(str(x)) == n)
print(f"{n}-digit ({len(group)}):", ", ".join(map(str, group)) if group else "none")
1-digit (10): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2-digit (0): none
3-digit (4): 153, 370, 371, 407
4-digit (3): 1634, 8208, 9474
5-digit (3): 54748, 92727, 93084
6-digit (1): 548834
7-digit (4): 1741725, 4210818, 9800817, 9926315
How many are there? A finite number. The On-Line Encyclopedia of Integer Sequences (sequence A005188) lists 89, counting 0, so 88 positive Armstrong numbers. The last and largest is 115132219018763992565095597973971522401, which has 39 digits. Why must the list end? From 61 digits up, even a number made entirely of 9s gives a digit-power sum (n × 9n) with fewer digits than the number itself, so no longer number can match; the lengths below that have been searched by computer.
Advanced Armstrong Number Programs
Finding First N Armstrong Numbers
This program generates the first N Armstrong numbers efficiently.
def find_n_armstrong(n):
armstrong_list = []
num = 0
while len(armstrong_list) < n:
digits = str(num)
num_digits = len(digits)
sum_of_powers = sum(int(d) ** num_digits for d in digits)
if sum_of_powers == num:
armstrong_list.append(num)
num += 1
return armstrong_list
# Find first 15 Armstrong numbers
first_15 = find_n_armstrong(15)
print("First 15 Armstrong numbers:")
print(first_15)
Interactive Menu-Driven Program
A complete program with multiple options for users.
def check_armstrong(num):
digits = str(num)
return sum(int(d) ** len(digits) for d in digits) == num
def find_in_range(start, end):
return [n for n in range(start, end + 1) if check_armstrong(n)]
def main():
while True:
print("\n--- Armstrong Number Program ---")
print("1. Check if a number is Armstrong")
print("2. Find Armstrong numbers in range")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == '1':
num = int(input("Enter number: "))
if check_armstrong(num):
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is not an Armstrong number.")
elif choice == '2':
start = int(input("Enter start: "))
end = int(input("Enter end: "))
result = find_in_range(start, end)
print(f"Armstrong numbers: {result}")
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
# Run the program
if __name__ == "__main__":
main()
Common Errors and How to Fix Them
Type Conversion Issues
Error: Trying to use string methods on integers or vice versa.
# Wrong
num = 153
for digit in num: # TypeError: int object is not iterable
# Correct
num = 153
for digit in str(num): # Convert to string first
print(digit)
Power Calculation Mistakes
Error: Using wrong exponent (fixed number instead of digit count).
# Wrong - always using power of 3
sum_of_powers = sum(int(d) ** 3 for d in str(num))
# Correct - using actual digit count
num_digits = len(str(num))
sum_of_powers = sum(int(d) ** num_digits for d in str(num))
Logic Errors in Digit Extraction
Error: Not properly extracting all digits with while loop.
# Wrong - infinite loop
while number > 0:
digit = number % 10
sum_of_powers += digit ** num_digits
# Missing: number = number // 10
# Correct
while number > 0:
digit = number % 10
sum_of_powers += digit ** num_digits
number = number // 10 # Remove last digit
Practice Exercises and Challenges
Beginner Level
Exercise 1: Write a program that checks if user input is an Armstrong number and displays the calculation step-by-step.
Exercise 2: Create a function that returns True only for 3-digit Armstrong numbers.
Exercise 3: Count how many Armstrong numbers exist between 1 and 10000.
Intermediate Level
Exercise 4: Implement an Armstrong number checker using recursion instead of loops.
Exercise 5: Create a program that finds the largest Armstrong number with exactly 4 digits.
Exercise 6: Build a function that validates user input and handles errors gracefully.
Advanced Level
Exercise 7: Optimize the range finder to skip impossible candidates (hint: mathematical properties can eliminate certain numbers).
Exercise 8: Create a class ArmstrongNumber with methods for checking, finding, and generating Armstrong numbers.
Exercise 9: Implement Armstrong number verification in different number bases (not just base 10).
Real-World Applications and Interview Questions
Armstrong numbers frequently appear in coding interviews to test fundamental programming skills.
Common interview questions:
- "Check if a given number is an Armstrong number" (Basic)
- "Find all Armstrong numbers between 1 and N" (Intermediate)
- "Generate the first N Armstrong numbers efficiently" (Advanced)
- "Optimize your solution for very large ranges" (Advanced)
Related mathematical concepts:
- Perfect numbers: Numbers equal to sum of their divisors
- Happy numbers: Numbers that eventually reach 1 through digit squaring
- Kaprekar numbers: Numbers with special digit properties
- Narcissistic numbers: General term for Armstrong-type numbers
These concepts build on similar programming techniques: digit manipulation, iterative checking, and mathematical validation.
Two natural next steps in the same spirit: the Fibonacci series written seven ways and reversing a string five ways, both with tested code and real output under every example.
Complete Code Example (Copy-Paste Ready)
Here's a complete, well-documented program you can use immediately:
def is_armstrong(number):
"""
Check if a number is an Armstrong number.
Args:
number (int): The number to check
Returns:
bool: True if Armstrong number, False otherwise
"""
digits = str(abs(number)) # Handle negative numbers
num_digits = len(digits)
sum_of_powers = sum(int(digit) ** num_digits for digit in digits)
return sum_of_powers == abs(number)
def find_armstrong_numbers(start, end):
"""Find all Armstrong numbers in a range."""
return [n for n in range(start, end + 1) if is_armstrong(n)]
def display_calculation(number):
"""Show the Armstrong number calculation step by step."""
digits = str(number)
num_digits = len(digits)
calculation = " + ".join(f"{d}^{num_digits}" for d in digits)
values = " + ".join(str(int(d) ** num_digits) for d in digits)
total = sum(int(d) ** num_digits for d in digits)
print(f"\nNumber: {number}")
print(f"Calculation: {calculation}")
print(f"Values: {values}")
print(f"Sum: {total}")
print(f"Result: {number} {'==' if total == number else '!='} {total}")
print(f"Armstrong: {is_armstrong(number)}")
# Example usage
print("=== Armstrong Number Checker ===\n")
# Check individual numbers
test_numbers = [153, 370, 9474, 123, 548834]
for num in test_numbers:
display_calculation(num)
# Find in range
print("\n=== Armstrong Numbers 1-1000 ===")
print(find_armstrong_numbers(1, 1000))
Armstrong numbers: common questions
A number equal to the sum of its digits, each raised to the power of how many digits it has. 153 is one: 13 + 53 + 33 = 153. They are also called narcissistic numbers or pluperfect digital invariants.
No. No number from 10 to 99 equals the sum of the squares of its digits; the program above checks every case.
153, 370, 371, 407.
4-digit: 1634, 8208, 9474. 5-digit: 54748, 92727, 93084.
There is only one: 548834. With 7 digits there are four: 1741725, 4210818, 9800817, 9926315.
89 counting 0 (88 positive ones), according to OEIS sequence A005188. The largest is 115132219018763992565095597973971522401, with 39 digits.
0 has one digit and 01 = 0, so by the definition it is, and OEIS includes it. Some textbooks start their lists at 1, so check which your teacher uses.
Turn the number into a string, count its digits, and compare the number with sum(int(d) ** len(s) for d in s). Method 2 above does exactly this in five lines.
Final Thoughts
Armstrong numbers provide an excellent foundation for practicing Python programming fundamentals. Through working with these numbers, you've learned how to manipulate digits, use loops effectively, apply mathematical operations, and think algorithmically.
The techniques you've learned digit extraction, power calculations, and iterative checking, are building blocks for more advanced programming concepts. Whether you're preparing for coding interviews, completing school assignments, or simply practicing Python, Armstrong numbers offer valuable hands-on experience.
Learn Python live, with a teacher reading your code
Programs like this are where loops, strings and maths meet. Ages 9 to 12: Python and AI for Kids. Ages 13 to 18: Python for Teens. College students and adults: Python Masterclass. The first class is a free demo, so you can see how it is taught before you decide.