Python Program to Find Armstrong Number in an Interval


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits in the number. In other words, if we take an n-digit number and add up the n-th power of each of its digits, the result will be the original number itself.

For example, 153 is an Armstrong number because it is a 3-digit number and:

1^3 + 5^3 + 3^3 = 153

Similarly, 9474 is an Armstrong number because it is a 4-digit number and:

9^4 + 4^4 + 7^4 + 4^4 = 9474


Python Code :

The below Python program finds all Armstrong numbers within a given interval:


# Function to check Armstrong number
def is_armstrong(num):
    # Convert number to string to count number of digits
    num_str = str(num)
    # Count number of digits
    num_digits = len(num_str)
    # Calculate sum of cubes of each digit
    armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)
    # Check if sum is equal to original number
    return armstrong_sum == num

# Function to find Armstrong numbers in an interval
def find_armstrong_numbers(start, end):
    # Iterate over numbers in the interval
    for num in range(start, end+1):
        # Check if number is an Armstrong number
        if is_armstrong(num):
            yield num

# Example usage
start = 1
end = 1000
print("Armstrong numbers in the interval [", start, ",", end, "]:")
for armstrong_num in find_armstrong_numbers(start, end):
    print(armstrong_num)

In the above code, the is_armstrong function is the same as in the previous example - it checks if a given number is an Armstrong number.

The find_armstrong_numbers function takes two arguments: start and end, which define the interval within which to find Armstrong numbers. It then iterates over all numbers in the interval using a for loop, and for each number, checks if it is an Armstrong number using the is_armstrong function.

If a number is an Armstrong number, it is yielded using the yield keyword, which allows us to iterate over the Armstrong numbers one by one.

Finally, we use the find_armstrong_numbers function to find all Armstrong numbers within an interval (in this case, the interval [1, 1000]) and print them to the console.

For example :


Armstrong numbers in the interval [ 1 , 1000 ]:
1
2
3
4
5
6
7
8
9
153
370
371
407


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co