Example to find an Armstrong number in Python in an interval

Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits

Formulae of Amstrong number is

ABC = A^ 3 + B^ 3 + C^ 3

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

= 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3

= 153

In this example, you will learn to write a Python program to print an Armstrong number between a range provided by a user.

lower = 100
upper = 2000

for num in range(lower, upper + 1):
    order = len(str(num))
    sum = 0
    for digit in str(num):
        sum += int(digit) ** order
    if num == sum:
        print(num)

Table of Contents

Output

153
370
371
407
1634

The program provided checks for Armstrong numbers in a given range. It takes two inputs, the lower and upper limit of the range, and then iterates over each number within the range to determine if it is an Armstrong number. 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.

Here We have used a for loop to iterate over each number in the range and another for loop to iterate over each digit in the number. We calculate the sum of the digits raised to the power of the order of the number, and checks if this sum is equal to the original number. If the sum is equal to the original number, the program prints it out as an Armstrong number.

When run with a lower limit of 100 and an upper limit of 2000, the program prints out all the Armstrong numbers in this range, which are 153, 370, 371, 407, and 1634.

Leave a Comment