- Sum
- 1^3 + 5^3 + 3^3 = 153
Check Armstrong Number in Python
What you’ll learn
- What an Armstrong number is, in simple school-level language.
- How to count digits and build digit-power sums in Python.
- One single-number checker and one range-printing program.
- Edge cases, complexity, and interview-ready explanations.
Overview
If a number equals the sum of its digits raised to the power of total digits, it is Armstrong. Example: 153 = 1^3 + 5^3 + 3^3.
What is an Armstrong number?
For a number n with k digits, split digits and compute: d1^k + d2^k + ... + dk^k. If the result is n, then n is Armstrong.
The important idea: the exponent is the same for every digit, and it equals the number of digits.
Intuition and examples
- Sum
- 1^3 + 2^3 + 3^3 = 36
- Reason
- Single digit: 7^1 = 7
Live preview
Enter a value and see the digit-power sum and verdict.
Algorithm
Goal: check if n is Armstrong.
Handle n <= 0
Return false for this tutorial.
Count digits
Find k = len(str(n)).
Sum powers
Add digit ** k for each digit.
Compare
If sum equals n, true; else false.
📜 Pseudocode
function isArmstrong(n):
if n <= 0:
return false
k = number of digits in n
sum = 0
for each digit d in n:
sum = sum + d^k
return sum == nCheck a single number
def is_armstrong(n: int) -> bool:
if n <= 0:
return False
power = len(str(n))
total = 0
temp = n
while temp > 0:
digit = temp % 10
total += digit ** power
temp //= 10
return total == n
number = 153
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")Armstrong numbers in a range
def is_armstrong(n: int) -> bool:
if n <= 0:
return False
power = len(str(n))
total = 0
temp = n
while temp > 0:
digit = temp % 10
total += digit ** power
temp //= 10
return total == n
start, end = 1, 200
print(f"Armstrong numbers in the range {start} to {end}:")
for value in range(start, end + 1):
if is_armstrong(value):
print(value, end=" ")❓ FAQ
Edge cases and pitfalls
Return false
This tutorial uses positive integers.
Do not lose it
Use a temp variable while extracting digits.
Big powers
Power sums grow fast; use careful constraints.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
| Single check | O(log n) | O(1) |
| Range 1..U | about O(U log U) | O(1) |
Summary
- Rule: digit-power sum equals the original number.
- Code: count digits, sum powers, compare.
- Practice: run on 153, 370, 371, 407 and nearby non-examples.
For 3-digit numbers, the Armstrong values are 153, 370, 371, and 407.
9 people found this page helpful
