Armstrong Numbers with Python

An Armstrong number is a special type of number where the sum of the cubes of the digits is equal to the number itself. Take 153, for example. (1*1*1) + (5*5*5) + (3*3*3) = 1+125+27 = 153 (the number itself). So, we can say that 153 is an Armstrong number. Now, an Armstrong number checker is usually considered a basic program every Pygrammer must know. So, here's how you can do it.

We first get the number input from the user. We need to first get the digits of the number. There are two ways you can do this. We can either use the mathematical method, where we get the last digit using the modulus operator, remove the final number by using an integer division, and repeat the process until all numbers are obtained. However, we can also do this by Python's string features and some basic type conversions. Once that's done, we need to find the sum of the cubes and check whether this sum is equal to the original number. Let's look at it in code now:


user_input = int(input("Enter the number to check: "))

#Splitting into Digits

#Mathematical Method

user_input_initial = user_input

sum_of_cubes_mm = 0

while(user_input > 0):
    sum_of_cubes_mm += (user_input%10)**3
    user_input = user_input // 10

if(user_input_initial == sum_of_cubes_mm):
    print("Yes, It's an Armstrong Number !")

else:
    print("No, It's not an Armstrong Number !")


#String Method

user_input_string = str(user_input_initial)

sum_of_cubes_sm = 0

for digit in user_input_string:
    sum_of_cubes_sm += (int(digit)**3)

if(user_input_initial == sum_of_cubes_sm):
    print("Yes, It's an Armstrong Number !")

else:
    print("No, It's not an Armstrong Number !")

Both methods work equally well. Decide whichever one you prefer and use it. 

So, now even you know how to find whether a number is an Armstrong number or not. Nice !

Do follow ThePygrammer if you found this post useful. Feel free to share if you think anyone else might find it useful. The comment section is open if you have any questions or suggestions. 

Until next time...


 

Comments