Hey guys, in this blog we will see a Python Program to Check Armstrong Numbers.
An Armstrong number is simply a number that equals the sum of the cube of all its digits. For example 371, it is an Armstrong number, and the following is the proof.
371 = (3)3 + (7)3 + (1)3
371 = 27 + 343 + 1
371 = 371
# Python program to check if the number 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")
Enter a number: 231 231 is not an Armstrong number
Enter a number: 407 407 is an Armstrong number
Enter a number: 371 371 is an Armstrong number
Here we are checking the same condition we defined above about Armstrong Numbers.
In our while loop,
- We are extracting digit by digit
- Cubing it
- Removing the extracted digit from our num
- And adding the cube to our sum
Suppose num = 371
So temp is also 371.
digit = temp%10 = 1
temp = temp//10 = 37
Check out our other python programming examples…