Program to Find Armstrong Numbers in a Given Range in Python
Armstrong Number in a Given Range
An Armstrong number (or 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, 153 and 9474 are Armstrong numbers.
We will explore a method to find Armstrong numbers within a given range using Python programming.
Method: Using a for Loop
We iterate through the given range and check each number for the Armstrong condition.
def is_armstrong(num): # Convert number to string to count digits num_str = str(num) num_digits = len(num_str) # Calculate the sum of digits raised to the power of num_digits sum_of_digits = sum(int(digit) ** num_digits for digit in num_str) return sum_of_digits == num # Get user input for range start = int(input("Enter the start of the range: ")) end = int(input("Enter the end of the range: ")) print(f"Armstrong numbers between {start} and {end} are:", end=" ") for i in range(start, end + 1): if is_armstrong(i): print(i, end=" ")
Output:
Enter the start of the range: 1 Enter the end of the range: 1000 Armstrong numbers between 1 and 1000 are: 1 153 370 371 407