A positive number is called an Armstrong number if it is equal to the sum of the cubes of its numbers, for example 0, 1, 153, 370, 371, 407, etc.
In other words, the following equation will be verified
xy..z = xn + yn + ….. + zn
n is the number of digits
For example, 370 is a 3-digit Armstrong number
370 = 33 + 73 + 03
= 27 + 343 + 0
Now, let’s see the implementation of Armstrong’s number in Python.
Program to check if the given number is an Armstrong number
# Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
print(num,"is not an Armstrong number")
Enter a number: 370
370 is an Armstrong number
Here’s a line-by-line explanation of the code:
num = int(input("Enter a number: ")): This line takes input from the user as an integer and stores it in the variable
sum = 0: This line initializes the
sumvariable with 0, which will be used to store the sum of the cubes of each digit.
temp = num: This line creates a copy of the
numvariable and stores it in
while temp > 0:: This line starts a while loop that continues until
tempis greater than 0.
digit = temp % 10: This line finds the last digit of
tempby using the modulo operator (
%), and stores it in the
sum += digit ** 3: This line adds the cube of
temp //= 10: This line updates the
tempvariable by removing the last digit, by using integer division (
if num == sum:: This line checks if the
numis equal to
print(num,"is an Armstrong number"): If the condition in line 8 is true, this line prints the message indicating that
numis an Armstrong number.
print(num,"is not an Armstrong number"): If the condition in line 8 is false, this line prints the message indicating that
numis not an Armstrong number.