Armstrong number is a number whose sum of ‘digits to the power of the number of digits’ is equal to the original number. E.g 153, 370, etc
Steps to Check Armstrong Number in Python
- Input a number.
- Count the number of digits in the number i.e
n
. - Calulate sum of digits with power of
n
. - If sum is equal to the original number then the number is Armstrong else not.
Check Whether a Number is Armstrong in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | num = int(input("Enter a numer \n")) temp = num n = 0 sumNum = 0 #counting number of digits in 'num' while temp>0: n +=1 temp = temp//10; temp = num #calculating sum of digit^n while temp>0: sumNum = sumNum + (temp%10)**n temp = temp//10 if sumNum == num: print("Armstrong Number \n") else: print("Not an Armstrong Number \n") |
Output
Print all Armstrong Numbers in the Interval in Python
To find Armstrong number in an interval we will use above program with for loop. Only we need to create a separate function and place the above code in it and call the function with loop number as an argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def checkArmstrong(num): temp = num n = 0 sumNum = 0 #counting number of digits in 'num' while temp>0: n +=1 temp = temp//10; temp = num #calculating sum of digit^n while temp>0: sumNum = sumNum + (temp%10)**n temp = temp//10 if sumNum == num: print(i) lower = int(input("Enter lower interval ")) upper = int(input("Enter upper interval ")) for i in range(lower,upper): checkArmstrong(i) |
Output
That’s all we need to write in python in order to check Armstrong’s number. Any doubts then comment below.