Python Program to Check Armstrong Number

In this example, we will write a simple program to take input number from the user and display whether the number is Armstrong number or not. To better understand this example, make sure you have knowledge of the following tutorials:-

Loading...

A positive integer is called Armstrong number of order n if
abcd… = an + bn + cn + dn + …

In case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example: 153 is an Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3.

The Armstrong number is also known as a narcissistic number.

Python Program to Check Armstrong Number for 3 digits

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

sum = 0

temp = number
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10

if number == sum:
   print(number, "is an Armstrong number")
else:
   print(number, "is not an Armstrong number")

The output of the above program is:-

Output 1

Enter a number: 153
153 is an Armstrong number

Output 2

Enter a number: 234
234 is not an Armstrong number

Python Program to Check Armstrong Number for n digits

number = int(input("Enter a number: "))
order = len(str(number))

sum = 0

temp = number
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

if number == sum:
   print(number, "is an Armstrong number")
else:
   print(number, "is not an Armstrong number")

The output of the above program is:-

Output 1

Enter a number: 1634
153 is an Armstrong number

Output 2

Enter a number: 1245
234 is not an Armstrong number

 

Program Explanation

The user provides the input for the number to check for the Armstrong number. We can use the len() function to get the order of number. Each number gets multiplied with order value using modulus operator(%) within the while loop. Finally, if the sum is equal to the number, then it is an Armstrong number.

Loading...
SHARE Python Program to Check Armstrong Number

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share