Python Program to Check Armstrong Number
sum(int(d)**len(str(num)) for d in str(num)) == num.Examples
How to Think About It
Algorithm
Code
num = int(input("Enter a number: ")) digits = len(str(num)) sum_of_powers = sum(int(d) ** digits for d in str(num)) 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 number
num = 153
Count digits
digits = 3 because '153' has 3 characters
Calculate sum of powers
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^3 | Running Sum |
|---|---|---|
| 1 | 1 | 1 |
| 5 | 125 | 126 |
| 3 | 27 | 153 |
Why This Works
Step 1: Count digits
We use len(str(num)) to find how many digits the number has, which is needed for the power calculation.
Step 2: Sum of powers
Each digit is raised to the power of the digit count and added together using a generator expression inside sum().
Step 3: Comparison
If the sum equals the original number, it means the number is an Armstrong number, so we print the positive result.
Alternative Approaches
num = int(input("Enter a number: ")) temp = num digits = len(str(num)) sum_of_powers = 0 while temp > 0: digit = temp % 10 sum_of_powers += digit ** digits temp //= 10 if sum_of_powers == num: print(f"{num} is an Armstrong number") else: print(f"{num} is not an Armstrong number")
def armstrong_sum(num, digits): if num == 0: return 0 return (num % 10) ** digits + armstrong_sum(num // 10, digits) num = int(input("Enter a number: ")) digits = len(str(num)) sum_of_powers = armstrong_sum(num, digits) if sum_of_powers == num: print(f"{num} is an Armstrong number") else: print(f"{num} is not an Armstrong number")
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, so the time depends linearly on the number of digits, which is O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The string-based approach is concise and fast for typical inputs, while the loop method avoids string conversion but is similar in speed; recursion is less efficient due to function call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String with sum() | O(d) | O(1) | Simplicity and readability |
| While loop with arithmetic | O(d) | O(1) | Traditional numeric processing |
| Recursion | O(d) | O(d) | Learning recursion, less efficient |