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
= 370
Now, let’s see the implementation of Armstrong’s number in Python.
Program to check if the given number is an Armstrong number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # 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") else: print(num,"is not an Armstrong number") |
Output:
1 2 3 4 | 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 variablenum.sum = 0: This line initializes thesumvariable with 0, which will be used to store the sum of the cubes of each digit.temp = num: This line creates a copy of thenumvariable and stores it intemp.while temp > 0:: This line starts a while loop that continues untiltempis greater than 0.digit = temp % 10: This line finds the last digit oftempby using the modulo operator (%), and stores it in thedigitvariable.sum += digit ** 3: This line adds the cube ofdigitto thesumvariable.temp //= 10: This line updates thetempvariable by removing the last digit, by using integer division (//).if num == sum:: This line checks if thenumis equal tosum.print(num,"is an Armstrong number"): If the condition in line 8 is true, this line prints the message indicating thatnumis an Armstrong number.print(num,"is not an Armstrong number"): If the condition in line 8 is false, this line prints the message indicating thatnumis not an Armstrong number.
