Python Program to Find Armstrong Number in an Interval

Python Program to Find Armstrong Number in an Interval | In this post, we will discuss how to find Armstrong numbers in a given range. Armstrong number is a number that when raised to the power of a number of its own digits is equal to the sum of that number.

Example of Armstrong Number:-

(i) Let’s assume a number as 9, the number of digits is 1 so 9 to the power of 1 is 9 there 9 is an Armstrong number. 

(ii) 371 – there are 3 digits so, each digit will be raised to 3
3*3*3 + 7*7*7 + 1*1*1 = 371. Therefore 371 is an Armstrong number.

Python Program to Find Armstrong Number in a Given Range

We can also set intervals to find the Armstrong number; this works as follows. Python code takes two intervals, upper limit and lower limit, and checks for the Armstrong number in between them.

# Python program to find armstrong number in an interval

# take range
low = 1
up = 250

# find armstrong number in range
for i in range(low, up +1):
   pow = len(str(i))
   sum = 0
   temp = i
   while temp > 0:
      digits = temp %10
      sum += digits ** pow
      temp //= 10
   if i == sum:
      print(i)

Output:

1
2
3
4
5
6
7
8
9
153

In the code, we have taken an interval from 1 to 250 so the output will be the Armstrong number between 1 to 250, We use a for loop to iterate the number between the range and then find the Armstrong number between the specified range.

Python Program to Find Armstrong Number in an Interval

In the previous program, the range is hardcoded in the program but in this program, we will find the Armstrong number in an interval given by the user.

# Python program to find armstrong number in an interval

# take range
low = int(input("Enter the lower limit: "))
up = int(input("Enter the upper limit: "))

# find armstrong number in range
for i in range(low, up +1):
   pow = len(str(i))
   sum = 0
   temp = i
   while temp > 0:
      digits = temp %10
      sum += digits ** pow
      temp //= 10
   if i == sum:
      print(i)

Output for the input values test-case-1:-

Enter the lower limit: 50
Enter the upper limit: 500
153
370
371
407

In the example given we have set the lower limit as low to 50 and the upper limit as up to 500 then by using a for loop we find the Armstrong number between 50 and 500 and print the same.

Output for the input values test-case-2:-

Enter the lower limit: 10
Enter the upper limit: 1000
153
370
371
407

In the example given we have set the lower limit as low to 10 and the upper limit as up to 1000 then by using a for loop we find the Armstrong number between 10 and 1000 and print the same.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *