How to Check Armstrong number in Python?


A number is called an Armstrong number if the sum of its own digits each raised to the power of the number of digits.

We can write in its generalized form as –

abcd..= an+bn+cn+dn+...

It is named after Michael F. Armstrong the Armstrong number is known with some other names –

  • Narcissistic number
  • pluperfect digital invariant (PPDI)
  • Plus perfect number

In this article, you will see the examples of Armstrong numbers and how to check if a number is Armstrong or not using the Python program.

Example of Armstrong number

A few examples of Armstrong number is given below.

153 is an Armstrong number that has 3 digits.

To verify this calculate the sum of the cube of each digit if should be equal to the given number i.e. 153

13+53+33 = 153

Similarly, 1634 is a four-digit Armstrong number you can verify this also by calculating the sum of its own digits each raised to the power 4 it should be equal to the given number i.e. 1634

14+64+34+44 = 1634

Some other examples are 1, 2, 3, 4, 5, 6, 7, 8, 9, 370, 371, 407, etc.

Python program to check for an Armstrong number

You can enter an n digit number to check if it is an Armstrong number or not. Now see the code below –

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

order = len(str(num))

# Calculate the sum of each digit raised to the power n
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

You can copy and save this code with the .py extension and then execute it and enter different numbers to check if the number is an Armstrong number or not.

Conclusion

In this article, you learned how to check if a number is an Armstrong number or not using the Python program. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.