Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Check Armstrong Number
An Armstrong number (also called a narcissistic number) is a positive integer that equals the sum of its own digits raised to the power of the number of digits. For example, 153 is a 3-digit Armstrong number because 1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
Understanding Armstrong Numbers
For a number with n digits, it's an Armstrong number if ?
abcd... = a^n + b^n + c^n + d^n + ...
Common examples include:
- 1-digit: 1, 2, 3, ..., 9 (all single digits)
- 3-digit: 153, 371, 407
- 4-digit: 1634, 8208, 9474
Method 1: Fixed 3-Digit Armstrong Number
This approach checks specifically for 3-digit Armstrong numbers ?
num = 153
sum_ = 0
temp = num
while temp > 0:
digit = temp % 10
sum_ += digit ** 3
temp //= 10
if num == sum_:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
153 is an Armstrong number
Method 2: General Armstrong Number (Any Digits)
This method works for Armstrong numbers of any length by calculating the number of digits first ?
def is_armstrong(num):
# Convert to string to count digits
str_num = str(num)
num_digits = len(str_num)
# Calculate sum of digits raised to power of num_digits
sum_of_powers = sum(int(digit) ** num_digits for digit in str_num)
return num == sum_of_powers
# Test with different Armstrong numbers
test_numbers = [153, 371, 1634, 221, 407]
for number in test_numbers:
if is_armstrong(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
153 is an Armstrong number 371 is an Armstrong number 1634 is an Armstrong number 221 is not an Armstrong number 407 is an Armstrong number
Method 3: Using Mathematical Approach
This method extracts digits using mathematical operations without string conversion ?
def count_digits(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong_math(num):
original = num
digits = count_digits(num)
sum_of_powers = 0
while num > 0:
digit = num % 10
sum_of_powers += digit ** digits
num //= 10
return original == sum_of_powers
# Test the function
number = 9474
if is_armstrong_math(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
9474 is an Armstrong number
Comparison
| Method | Flexibility | Readability | Performance |
|---|---|---|---|
| Fixed 3-digit | Limited | Simple | Fastest |
| String conversion | High | Very clear | Moderate |
| Mathematical | High | Complex | Good |
Conclusion
Armstrong numbers are equal to the sum of their digits raised to the power of digit count. Use string conversion for readability or mathematical approach for pure numeric operations without string handling.
