Python Program to Check Armstrong Number (original) (raw)
Last Updated : 29 May, 2026
Given a number n, the task is to check whether it is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of its digits raised to the power of the total number of digits. For example:
Input: n = 153
Output: Armstrong Number
Explanation: 13 + 53 + 33 = 153
Let’s explore different methods to check Armstrong numbers.
Using a Mathematical Approach
This approach extracts digits using arithmetic operations and calculates the sum of digits raised to the required power. The final sum is then compared with the original number.
Python `
n = 153 t = n p = len(str(n)) s = 0
while t > 0: d = t % 10 s += d ** p t //= 10
if s == n: print("Armstrong Number") else: print("Not an Armstrong Number")
`
**Explanation:
- len(str(n)) finds the total number of digits and t % 10 extracts the last digit of the number.
- d ** p raises the digit to the required power and t //= 10 removes the last digit in each iteration.
Using String Conversion
This approach converts the number into a string and loops through each digit directly. Each digit is converted back to an integer for calculation.
Python `
n = 153 p = len(str(n)) s = sum(int(d) ** p for d in str(n))
if s == n: print("Armstrong Number") else: print("Not an Armstrong Number")
`
**Explanation:
- str(n) converts the number into a string and for d in str(n) accesses each digit one by one.
- int(d) ** p raises each digit to the required power and sum() adds all powered digit values together.
Using map() and lambda
This approach uses map() and lambda to process each digit and calculate the Armstrong sum in a compact way.
Python `
n = 153 p = len(str(n)) s = sum(map(lambda d: int(d) ** p, str(n)))
if s == n: print("Armstrong Number") else: print("Not an Armstrong Number")
`
**Explanation:
- str(n) converts the number into a string and map() applies the lambda function to each digit.
- lambda d: int(d) ** p raises each digit to the required power and sum() adds all calculated values together.
Using Recursion
This approach calculates the Armstrong sum recursively by processing one digit at a time until the number becomes 0.
Python `
n = 153 p = len(str(n))
def arm(x): if x == 0: return 0 return (x % 10) ** p + arm(x // 10)
if arm(n) == n: print("Armstrong Number") else: print("Not an Armstrong Number")
`
**Explanation:
- x % 10 extracts the last digit of the number and x // 10 removes the last digit in each recursive call.
- The function keeps adding powered digits recursively. Recursion stops when the number becomes 0.