Python Program to Find Armstrong Number between an Interval
In this tutorial, we are going to learn how to find Armstrong Number between an interval in Python. It is very simple if we know what is Armstrong Number. Let’s see
Find Armstrong Number between an Interval in Python
A number is said to be an Armstrong Number if the sum of all the individual digits in that number, each raised to the power of n is equal to the original number. Where n is the total number of digits in that number.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
For example:
153
1*1*1 + 5*5*5 + 3*3*3= 153
so it is Armstrong Number.
16
1*1 + 6*6 = 37
so it is not an Armstrong Number.
lower_limit=int(input("lower limit: ")) upper_limit=int(input("upper limit: ")) temp=0 if(lower_limit>upper_limit): temp=lower_limit lower_limit=upper_limit upper_limit=temp print("Armstrong Numbers are: ") for number in range(lower_limit,upper_limit+1): #y+1 to include upper_limit in the calculation digits=0 temp=number while temp>0: # calculating total number digits=digits+1 temp=temp//10 sum=0 temp=number while temp>0: # calculate armstrong number last_digit=temp%10 sum=sum+(last_digit**digits) temp=temp//10 if number == sum: print(number)
Code Explanation :
- First, the user is asked to enter the value of the lower limit and upper limit.
- In (line 3) we are taking temp as a new variable so that we can perform swapping. Here, the reason for the swapping is to avoid corner cases like if the user enters the lower limit as 200 and the upper limit as 100 then the code won’t give any output.
- Loop traversal from the lower limit to the upper limit.
- Counts the number of individual digits and divide the given number into individual digits.
- Calculate the power of n(total digits in a given number) for each individual and add those numbers.
- Compare the original value with Sum value. If they are equal then print the Number and it is Armstrong number.
Output: lower limit: 153 upper limit: 1 Armstrong Numbers are: 1 2 3 4 5 6 7 8 9 153
I hope you really enjoy this tutorial and feel free to leave a comment if you have any doubt.
You may also learn:
Leave a Reply