Python Program to Find Armstrong Number
sum(int(digit) ** len(str(num)) for digit in str(num)) == num.Examples
How to Think About It
Algorithm
Code
num = int(input('Enter a number: ')) digits = str(num) power = len(digits) sum_of_powers = sum(int(d) ** power for d in digits) if sum_of_powers == num: print(f'{num} is an Armstrong number') else: print(f'{num} is not an Armstrong number')
Dry Run
Let's trace the number 153 through the code
Input and convert to string
num = 153, digits = '153'
Count digits
power = 3
Calculate sum of powers
1**3 + 5**3 + 3**3 = 1 + 125 + 27 = 153
Compare sum with original
153 == 153 is True
Print result
'153 is an Armstrong number'
| Digit | Digit^Power | Running Sum |
|---|---|---|
| 1 | 1^3 = 1 | 1 |
| 5 | 5^3 = 125 | 126 |
| 3 | 3^3 = 27 | 153 |
Why This Works
Step 1: Counting digits
We convert the number to a string to easily count how many digits it has using len().
Step 2: Raising digits to power
Each digit is raised to the power of the total digits because Armstrong numbers are defined this way.
Step 3: Comparing sum to original
If the sum of these powered digits equals the original number, it confirms the number is Armstrong.
Alternative Approaches
num = int(input('Enter a number: ')) original = num power = len(str(num)) sum_of_powers = 0 while num > 0: digit = num % 10 sum_of_powers += int(pow(digit, power)) num //= 10 if sum_of_powers == original: print(f'{original} is an Armstrong number') else: print(f'{original} is not an Armstrong number')
num = int(input('Enter a number: ')) power = len(str(num)) digits = list(map(int, str(num))) sum_of_powers = sum(d ** power for d in digits) print(f'{num} is an Armstrong number' if sum_of_powers == num else f'{num} is not an Armstrong number')
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through each digit once, so time grows linearly with the number of digits, O(n).
Space Complexity
Converting the number to a string and storing digits uses O(n) space, where n is the number of digits.
Which Approach is Fastest?
All approaches have similar time complexity; using string iteration is simpler and more readable, while the loop with math.pow is more manual but avoids string overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String iteration with sum and comprehension | O(n) | O(n) | Simplicity and readability |
| While loop with math.pow | O(n) | O(1) | Manual control, no string conversion |
| List comprehension with map | O(n) | O(n) | Explicit digit conversion, clear code |