An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 371 is an Armstrong number because 33 + 73 + 13 = 371. In this tutorial, we will learn how to check if a number is an Armstrong number in Python using several methods including functions, for loops, while loops, recursion, and list comprehension.
Python Program to Check Armstrong Number Using Functions
One way to check if a number is an Armstrong number is to use a function. We can define a function called “is_armstrong” that takes in a number and returns True if the number is an Armstrong number and False if it is not. Here is an example of how this function can be implemented in Python:
def is_armstrong(num):
num_str = str(num)
num_len = len(num_str)
sum = 0
for i in range(num_len):
sum += int(num_str[i])**num_len
return sum == num
# test the function
print(is_armstrong(371)) # True
print(is_armstrong(407)) # False
Python Program to Find Armstrong Number in an Interval
To find all the Armstrong numbers within a given interval, we can use a for loop. For example, to find all the Armstrong numbers between 1 and 1000, we can use the following code:
for num in range(1, 1001):
if is_armstrong(num):
print(num)
Python Program to Check Armstrong Number Using a While Loop
We can also use a while loop to check if a number is an Armstrong number. Here is an example of how this can be done:
def is_armstrong(num):
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += digit**3
temp //= 10
return sum == num
# test the function
print(is_armstrong(371)) # True
print(is_armstrong(407)) # False
Python Program to Check Armstrong Number Using Recursion
Recursion is a programming technique in which a function calls itself with a modified input until a base case is reached. We can use recursion to check if a number is an Armstrong number by defining a recursive function that calculates the sum of the digits raised to the power of the number of digits. Here is an example of how this can be done in Python:
def is_armstrong(num):
if num < 10:
return num**3
else:
return (num%10)**3 + is_armstrong(num//10)
# test the function
print(is_armstrong(371)) # 371
print(is_armstrong(407)) # 407
Python Program to Check Armstrong Number Using List Comprehension
List comprehension is a concise way to create a list using a single line of code. We can use list comprehension to check if a number is an Armstrong number by creating a list of the digits raised to the power of the number of digits and then checking if the sum of the list is equal to the original number. Here is an example of how this can be done in Python:
def is_armstrong(num):
return num == sum([int(digit)**len(str(num)) for digit in str(num)])
# test the function
print(is_armstrong(371)) # True
print(is_armstrong(407)) # False