Javaexercise.com

Python Program to Check Armstrong Number

An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. It means a number is called Armstrong if the sum of its digit to the power of the number of digits is equal to the number itself.

For example, 153 is an Armstrong number because 1^n+5^n+3^n = 153. Where n is the total number of digits in the number. Let's understand by some examples. We can check a number of n-digit for Armstrong number.

If you want to test a number in which digits are fixed then you can use this example. This example is suitable for the three digits number.

Python Program to Check Armstrong Number

# Python Program to Find Armstrong Number for 3 digit number
number = input("Enter a Number")
number = int(number)
sum_of_digits = 0
temp = number
# Finding Armstrong number
while number > 0:
   digit = number % 10
   sum_of_digits += digit ** 3
   number //= 10
if(temp == sum_of_digits):
   print("It is an Armstrong number")
else:
   print("It is not an Armstrong number")

Output:

Enter a Number 153
It is an Armstrong number

 

Check Armstrong Number in Python

This program can check Armstrong number for n number of digits. Here, we used the len() function to get the number of digits in a number and then convert the number into an integer to perform mathematical operations. 

# Python Program to Find Armstrong Number for n digit number
number = input("Enter a Number")
no_of_digits = len(number)
number = int(number)
sum_of_digits = 0
temp = number
# Finding Armstrong number
while number > 0:
   digit = number % 10
   sum_of_digits += digit ** no_of_digits
   number //= 10
if(temp == sum_of_digits):
   print("It is an Armstrong number")
else:
   print("It is not an Armstrong number")

Output:

Enter a Number 548834
It is an Armstrong number

Enter a Number 25485
It is not an Armstrong number