A Number is Armstrong Number or Not in Python

In this Python example, we will cover the program to check whether a given number is an Armstrong number or not. Let’s begin.

1. What is An Armstrong Number?

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.

– WikiPedia

A given positive number is said to be an Armstrong number, if :

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

Input : 1634 
Output : Yes 
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Input : 120
Output : No
1*1*1 + 2*2*2 + 0*0*0 = 9

Some of the topics which will be helpful for understanding the program implementation better are:

2. Python Program to check Armstrong Number

In the program, we have created 3 different functions.

  • The first is the function to check the Armstrong number named as check_Armstrong()
  • The second is to get the order of the number named as get_order() and
  • The third one is to get the power of res value with order n named as get_power().
# Python program to check Armstrong Number
def get_power(a, b):
  if b== 0:
    return 1
  if b % 2 == 0:
    return get_power(a, b // 2) * get_power(a, b // 2)
  return a * get_power(a, b // 2) * get_power(a, b // 2)

def get_order(num):
  n = 0
  while (num != 0):
    n = n + 1
    num = num // 10
  return n

def check_Armstrong(num):
  n = get_order(num)
  temp = num
  sumvalue = 0
  while (temp != 0):
    res = temp % 10
    sumvalue = sumvalue + get_power(res, n)
    temp = temp // 10
  if sumvalue == num:
    return "Yes, the given number is Armstrong Number"
    return "No, the given number is not Armstrong Number"

num = int(input("Enter the number to check for Armstrong: "))
if num > 0:
  print("Wrong input")
Enter the number to check for Armstrong: 153
Yes, the given number is Armstrong Number

Here, the program can check for any positive value of any order. The program is not limited to the three-digit numbers, rather it can check the number of any order.

3. Conclusion

In this article, we discussed the best way to check if a given number is an Armstrong number or not using the functions and loop.

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x