Python Program to Find All Armstrong Numbers in Range
for num in range(start, end+1): if num == sum(int(d)**len(str(num)) for d in str(num)): print(num).Examples
How to Think About It
Algorithm
Code
start = int(input('Enter start of range: ')) end = int(input('Enter end of range: ')) for num in range(start, end + 1): digits = str(num) power = len(digits) total = sum(int(d) ** power for d in digits) if num == total: print(num, end=' ')
Dry Run
Let's trace the number 153 through the code to see why it is an Armstrong number.
Convert number to string
digits = '153'
Count digits
power = 3
Calculate sum of digits raised to power
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Compare sum to original number
153 == 153 → True, so 153 is printed
| Number | Digits | Power | Sum of digits^power | Is Armstrong? |
|---|---|---|---|---|
| 153 | 1,5,3 | 3 | 153 | Yes |
| 154 | 1,5,4 | 3 | 1 + 125 + 64 = 190 | No |
Why This Works
Step 1: Convert number to string
We convert the number to a string to easily access each digit.
Step 2: Count digits
The number of digits determines the power to which each digit is raised.
Step 3: Sum digits raised to power
Each digit is raised to the power of the digit count and summed to check if it equals the original number.
Alternative Approaches
def is_armstrong(num): digits = str(num) power = len(digits) return num == sum(int(d)**power for d in digits) start, end = 1, 500 for n in range(start, end+1): if is_armstrong(n): print(n, end=' ')
import math start, end = 1, 500 for num in range(start, end+1): digits = str(num) power = len(digits) total = sum(int(d) ** power for d in digits) # math.pow returns float, so ** is preferred if num == total: print(num, end=' ')
Complexity: O(n * k) time, O(k) space
Time Complexity
The program checks each number in the range (n numbers). For each number, it processes each digit (k digits), so total time is O(n * k).
Space Complexity
Space is mainly used to store the string form of the number and temporary sums, which is O(k), where k is the number of digits.
Which Approach is Fastest?
Using the direct ** operator is faster and simpler than math.pow. Separating the check into a function improves readability but does not affect complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Inline check with ** operator | O(n * k) | O(k) | Simple scripts and beginners |
| Function-based check | O(n * k) | O(k) | Readability and reuse |
| Using math.pow | O(n * k) | O(k) | Avoided due to float overhead |