An Armstrong Number (also known as a narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits.
For example:
- The number 153 is an Armstrong number because:
153 = 13 + 53 +33 = 1 + 125 + 27 = 153 - The number 154 is NOT an Armstrong number because
154 = 13 + 53 +43 = 1 + 125 + 64 = 190
This article describes different methods to check if the number is Armstrong or not using Python.
Table of contents
1. How to check Armstrong number in Python
Steps to check Armstrong number using loop and string conversion:
- Convert a number to a string
Convert a number to a string using built-in
str()function to access each digit individually.
For Example,str(153) = '153' - Count Digits in a number
Determine the number of digits in the number using Python’s built-in
len()function.
For Example,len('153') = 3 - Calculate Sum of Powers
Loop through each digit, convert it back to an integer, and raise it to the power of the total number of digits. The sum of these powers is accumulated.
For Example,153 = 13 + 53 +33 = 1 + 125 + 27 = 153 - Comparison
The sum of powers is compared with the original number. If they are equal, the number is an Armstrong number.
Code Example:
2. Using Mathematical Operation
With this method, we check whether a number is an Armstrong number using mathematical operations like exponentiation (**), modulus (%), and floor division (//).
Code Example:
Explanation:
- Initial Variables:
number = 153: The number we’re testing to see if it’s an Armstrong number.temp = number: A copy of the original number (153), used for calculations without changing the original value.num_digits = len(str(number)): It converts the number to a string (“153”) and measures its length (3).sum_of_powers = 0: This variable will store the sum of each digit raised to the power ofnum_digits.
- While Loop:
- The loop runs as long as temp is greater than 0. It extracts the digits of the number one by one and processes them:
digit = temp % 10: Extracts the last digit of temp. For 153, the last digit is 3.sum_of_powers += digit ** num_digits: Raises the digit to the power of num_digits (3 in this case) and adds it to sum_of_powers. For 3, this would be33 = 27temp //= 10: Removes the last digit from temp by doing integer division. This reduces 153 to 15, then to 1, and eventually to 0.
- Checking if Armstrong:
- After the loop, the program compares
sum_of_powersto the originalnumber. If they are equal, the number is an Armstrong number; otherwise, it is NOT an Armstrong number.
- After the loop, the program compares
3. Using Recursion
Recursion is a programming technique where a function calls itself to solve smaller instances of a problem until a base condition is met.
To check Armstrong number in Python, this method uses recursion to calculate the sum of the digits raised to the power of the number of digits.
Example Execution for 153:
153 = 13 + 53 +33 = 1 + 125 + 27 = 153
Recursion steps:
- 153 → last digit 3 →
3^3 = 27→ callsum_of_powers_recursive(15, 3) - 15 → last digit 5 →
5^3 = 125→ callsum_of_powers_recursive(1, 3) - 1 → last digit 1 →
1^3 = 1→ callsum_of_powers_recursive(0, 3) - 0 → base case → return
0 - Summing up:
1 + 125 + 27 = 153 - Compare the original number 153 to the summation output. If they are equal, then it’s an Armstrong number.
Code Example:
Explanation:
- The number of digits (
num_digits) is calculated usinglen(str(number)). sum_of_powers_recursive(number, num_digits):- This function takes a number (153) and the number of digits (3) as arguments.
- If the number is 0, the recursion stops.
- Otherwise,
- It extracts the last digit (
number % 10) (i.e., 153 % 10 = 3) - Raises it to the power of
num_digitsi.e.,33= 27 - Adds this value to the recursive call on the rest of the digits (
number // 10) (i.e.,153 // 10 = 15). - And it continues till the number reaches 0.
- It extracts the last digit (
- It recursively calculates the sum of each digit raised to the power of the number of digits
(33 + 53 + 13 ).
is_armstrongchecks if the original number equals the sum of its digits raised to the power of the number of digits.- If true, the number is printed as an Armstrong number; otherwise, it is not.
4. Using Python’s map and lambda functions
This method leverages Python’s map() and sum() functions and a lambda expression for a concise solution to check if the given number is an Armstrong number.
- A lambda function in Python is a small, anonymous function that can have multiple arguments but only one expression, which is evaluated and returned.
For Example,square = lambda x: x ** 2
print(square(5)) # Output: 25 - The
map()function in Python applies a given function to all items in an iterable (list, tuple, etc.) and returns a new iterator with the transformed values.
For Example,squared = list(map(lambda x: x ** 2,[1, 2, 3, 4]))print(squared) # Output: [1, 4, 9, 16] - The
sum()function in Python returns the sum of all elements in an iterable (list, tuple, set, etc.).
For Example,sum = sum(list(map(lambda x: x ** 2, [1, 2, 3, 4])))
print (sum) # Output: [1, 4, 9, 16]
Code Example:
Explanation:
len(str(number)): It converts the number into string and calculates the length of the string, which tells us how many digits the number has. In this case, it returns 3, since ‘153’ has three characters.sum(map(lambda x: int(x) ** num_digits, str(number))):str(number): Again, this converts the number into a string so we can access each digit individually.lambda x: int(x) ** num_digits: This is a small anonymous function (a lambda function) that takes each digitx(as a string), converts it to an integer, and raises it to the power of num_digits.- The
map()function applies a lambda expression to each digit, which raises it to the power of the number of digits.
So, for ‘153’, the map function will compute:13=1, 53=125, 33=27
- The
sum()function adds up all the values produced by the map function.
In this case, it calculates:1 + 125 + 27 = 153 - Finally, we check if the out from the
sum()function is equal to the original number is equal to the original number. If they are equal, the result is True; otherwise, it is False.
5. Using List Comprehension
List comprehension is a concise way to create Python lists by applying an expression to each item in an iterable, with optional filtering using a condition.
In this approach, to check the Armstrong number, the logic is similar to the loop method using string conversion but uses list comprehension for a more Pythonic approach to find Armstrong numbers.
Explanation:
len(str(number)): It converts the number into string and calculates the length of the string, which tells us how many digits the number has. In this case, it returns 3, since ‘153’ has three characters.[int(digit) ** num_digits for digit in str(number)]:- This is a list comprehension, which is a compact way to generate a list.
- for digit in
str(number): Loops through each character (digit) in the string representation of the number (‘153’). So, it loops over ‘1’, ‘5’, and ‘3’. int(digit): Converts each character back into an integer.int(digit) ** num_digits: Raises each digit to the power ofnum_digits(which is 3 in this case).- For
153, this list comprehension creates the list[1^3, 5^3, 3^3], which is[1, 125, 27].
- The
sum()function adds up all the values in the list.
For[1, 125, 27], it calculates:1 + 125 + 27 = 153 - Finally, we check if the result from the
sum()function is equal to the original number (i.e., if the sum of the digits raised to the power ofnum_digitsis equal to the original number.) If they are equal, the result is True; otherwise, it is False.
Summary
This article explored diverse Python methods for determining if a number is an Armstrong number. It began with the foundational while loop approach, demonstrating how to extract digits and calculate their powers iteratively. It then transitioned to more Pythonic techniques, showcasing the power of string conversion and for loops for concise and efficient solutions. The article also touched upon the less common, but conceptually interesting, recursive implementation, highlighting the flexibility of Python’s function call mechanism.
These are different ways to determine whether a given number is an Armstrong number in Python. You can choose the one that best suits your requirements, whether it’s clarity, conciseness, or efficiency.
The Mathematical Operations approach is the most efficient in terms of time and space.
- Loop and string conversion:
- Advantage: Efficient, avoids recursion
- Mathematical Operation:
- Advantage: Efficient and avoids unnecessary string operations.
- Recursion:
- Advantage: Mimics the natural mathematical formula for Armstrong numbers.
map()function and lambda:- Advantage: Uses functional programming, making the code clean and compact.
- List comprehension:
- Advantage: Short and elegant, following a Pythonic approach.

Leave a Reply