Problem: Write a Python program to check whether the given number is Armstrong or not.

A number is said to be Armstrong if the sum of its digits power its order (number of digits) is equal to the original number.

For examples: 153, 370, etc.

Armstrong number in Python

Steps to Check Armstrong Number

  1. Input a number
  2. Count the number of digits in the number.
  3. Compute the sum of each digit raised to the power total number of digits.
  4. If the calculated sum is equal to the input number, then the number is Armstrong otherwise not.

Here is the implementation of the steps in Python:

num = int(input("Enter a number: \n"))

#count digits in 'num'
n = len(str(num))
    
temp = num
sumNum = 0

#calculate sum of digits raised to the power 'n'
while temp>0:
    sumNum = sumNum + (temp%10)**n
    temp = temp//10

#check if sum equals the original number
if sumNum == num:
    print("Armstrong Number \n")
else:
    print("Not an Armstrong Number \n")

Output:

Enter a number:
153
Armstrong Number

Print all Armstrong Numbers in the Given Interval

To find all Armstrong numbers in the given interval, we check each number using the same logic used in the above program.

For this, we write the logic to check Armstrong’s number in a separate function and call the same for every number using a loop.

def isArmstrong(num):
    #count digits in 'num'
    n = len(str(num))
        
    temp = num
    sumNum = 0
    
    #calculate sum of digits raised to the power 'n'
    while temp>0:
        sumNum = sumNum + (temp%10)**n
        temp = temp//10
    
    #check if sum equals the original number
    return sumNum == num

lower = int(input("Enter lower interval value: "))
upper = int(input("Enter upper interval value: "))

for i in range(lower,upper):
    if isArmstrong(i):
        print(i)

Output:

Enter lower interval value: 1
Enter upper interval value: 1000
1 2 3 4 5 6 7 8 9 153 370 371 407

Leave a Reply