In this tutorial, we will learn how to find all Armstrong numbers in a given interval in Python. We will cover the definition of an Armstrong number and implement a function to identify Armstrong numbers within a specified range.
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.
The syntax to find Armstrong numbers in an interval in Python is:
def is_armstrong(number):
digits = [int(d) for d in str(number)]
power = len(digits)
total = sum(d ** power for d in digits)
return total == number
for num in range(start, end + 1):
if is_armstrong(num):
print(num)
We can create a function to check if a number is an Armstrong number and use it to find all Armstrong numbers within a specified range.
For example,
is_armstrong
that takes one parameter number
.True
if the computed sum equals the original number, otherwise return False
.for
loop to iterate through the numbers in the interval.is_armstrong
function to check if the current number is an Armstrong number. If true, print the number.def is_armstrong(number):
digits = [int(d) for d in str(number)]
power = len(digits)
total = sum(d ** power for d in digits)
return total == number
# Define the interval
start = 100
end = 1000
# Print all Armstrong numbers in the interval
for num in range(start, end + 1):
if is_armstrong(num):
print(num)
153 370 371 407