python

Check Armstrong Number using Python

In this post, we are going to explain multiple methods that can be used to check if a given value is an Armstrong number or not.

# define the number taht we want to check
number = 153

# initialize required variable
sum = 0
temp = number
n = len(str(number))

while temp > 0:
  val = temp % 10
  sum += val ** n
  temp //= 10

print("Number is: ", number)
print("Sum is: ", sum)

if number == sum:
  print("{} is an Armstrong number".format(number))
else:
  print("{} is not an Armstrong number".format(number))

Output

Number is:  153
Sum is:  153
153 is an Armstrong number

If there is an integer type number and it contains n digits then the sum of each digit after multiplying it to itself n times is equal to the number itself then the number will be considered as Armstrong number.

If we have a number let's say XYZ and we want to know if it is an Armstrong number or not then we will apply the below calculation to it.

XYZ = (X*X*X) + (Y*Y*Y) + (Z*Z*Z)

If the LHS is equal to RHS then the number is Armstrong number otherwise not.

For example, in the previous code example, we have a value of 153 that we want to check if it Armstrong number or not. We will perform the below calculation on it.

153 = (1*1*1) + (5*5*5) + (3*3*3)

So here, we found the sum after multiplying the number itself 3 times will be equal to 153 so 153 is an Armstrong number.

Create a function in Python that will check Armstrong number

# create a function that cehck if the given value is Armstrong Number
def check_armstrong_number(number):
  sum = 0
  temp = number
  n = len(str(number))
  
  while temp > 0:
    val = temp % 10
    sum += val ** n
    temp //= 10
  
  if number == sum:
    print("{} is an Armstrong number".format(number))
  else:
    print("{} is not an Armstrong number".format(number))


# test the above function
check_armstrong_number(127)
check_armstrong_number(153)

Output

127 is not an Armstrong number
153 is an Armstrong number
Was this helpful?