Python - Check Armstrong Number

Armstrong number is a number that is equal to the sum of cubes of its digits.
For example 0,1,153,371 and 407 are the Armstrong numbers.

Let's understand how 153 is an Armstrong number.

    153 = (1*1*1) + (5*5*5) + (3*3*3), 
    
    where

    (1*1*1) = 1
    (5*5*5) = 125
    (3*3*3) = 27
    
    Hence, 1+ 125 + 27 = 153

In this program, you will learn how to check Armstrong number.


Program Code



    # Enter the number
    num = int(input('Enter the  number to check the Armstrong number: '))

    # Find the number of digits
    order = len(str(num))

    # Initialize sum
    sum = 0

    # Find the sum of the cube of each digit
    temp = num
    while temp > 0:
        digit = temp % 10
        sum += digit ** order
        temp = temp // 10

    # Display the result
    if num == sum:
        print(num, 'is an Armstrong number')
    else:
        print(num, 'is not an Armstrong number')

Output1



    Enter the  number to check the Armstrong number: 371
    371 is an Armstrong number

Output2



    Enter the  number to check the Armstrong number: 249
    249 is not an Armstrong number

In this program, we have initialized the sum to 0 and obtain each digit number by using the modules operator %. The remainder of a number is the last digit of that number when it is divided by 10. We will calculate the cubes using exponent operator and sum of them.

Finally, we compare the sum with the original number and consider it is Armstrong number if they are equal.



The following topics can be useful to understand this program.



Related Tutorials