Python program to check armstrong number

In this post, we will see how to check if number is Armstrong number.
Armstrong number is a 3 digit number which is equal to sum of cube of its digits.
For example: 371,153

Let’s write a simple python program to check armstrong number.

def isArmStrong(num): sum=0; tempNum=num while(tempNum!=0): remainder=tempNum%10 sum+=(remainder**3) tempNum//=10 if(sum==num): return True else: return False # Testing the function print("Is 371 armstrong number : ",isArmStrong(371)) print("Is 134 armstrong number : ",isArmStrong(134)) print("Is 134 armstrong number : ",isArmStrong(153))

Output:

Is 371 armstrong number : True
Is 134 armstrong number : False
Is 134 armstrong number : True

Let’s understand the program.

  • Initialize sum with 0
  • Iterate over while loop and find the remainder
  • calculate cube of remainder and Add to the sum. If you look closely we are actually adding cube of each digit
  • tempNum//=10 -> With this step, we are removing most less significant digit in each iteration

That’s all about Python program to find armstrong number.

Leave a Reply

Your email address will not be published. Required fields are marked *