Python Program to Find Armstrong Numbers Within an Interval. An Armstrong number also known 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. This interesting property makes Armstrong numbers a popular topic in introductory programming courses. In this tutorial, we will write a Python program that can find all Armstrong numbers in a given interval.
Table of Contents
Writing the Python Program
The main component of our Python program will include:
- A function to determine if a number is an Armstrong number.
- A loop to iterate through an interval and apply the function.
Function to Check Armstrong Numbers
Let’s start by writing a Python function to check if a number er is an Armstrong number.
def is_armstrong(number):
# Convert the number to a string to easily iterate over digits
digits = str(number)
power = len(digits)
sum_of_powers = sum(int(digit)** power for digit in digits)
return sum_of_powers == number
This function converts the number to a string to loop through each digit, raises it to the power of the number of digits, sums these values, and checks if the sum is equal to the original number.
Finding Armstrong Number in an Interval
Now, We need to define our interval and use a loop to find all Armstrong numbers within the given range.
def find_armstrong_number(start,end):
armstrong_numbers = []
for number in range (start,end+1):
if is_armstrong(number):
armstrong_numbers.append(number)
return armstrong_numbers
This function iterates through each number in the specified interval and checks if it is an Armstrong number using our 'is_armstrong'
function. If it is, the number is added to the list 'armstrong_number'
.
Running the Program
Finally, Let’s put it all together and run our function for a specific interval.
start = 100
end = 1000
# find and print all armstrong numbers in the interval
armstrong_in_interval = find_armstrong_number(start,end)
print(armstrong_in_interval)
Congratulations, you now have a Python script capable of identifying Armstrong numbers within a given interval.
Happy Coding & Learning
See Also
2 thoughts on “Python Program to Find Armstrong Numbers Within an Interval”