check armstrong number in python example

In this example, you will learn to check whether number is Armstrong or not based on user input.

A number is said to be an Armstrong number when the sum of the nth power of each digit is equal to the number itself. Here, 'n' is the number of digits of the given number.

For example, an Armstrong number of three digits is an integer, such that the sum of the cubes of its digits is equal to the number itself.

Example :

#Python program to check whether the given number is Armstrong or not

from math import *
number = int(input("Enter the number : "))
result = 0
n = 0
temp = number;
while (temp != 0):
    temp =int(temp / 10)
    n = n + 1

#Checking if the number is armstrong
temp = number
while (temp != 0):
    remainder = temp % 10
    result = result + pow(remainder, n)
    temp = int(temp/10)
if(result == number):
    print("Armstrong number")
    print("Not an Armstrong number")

Output :

Enter the number : 371
Armstrong number

Explanation :

First of all this program will ask user to input a number and store it into number variable. Then it divide number with 10 and find reminder and calculate cube of reminder. This process loops till entered number is greater then zero. At last, if sum of reminders and inputted number is equal then it will print number is Armstrong otherwise it will print number is not Armstrong.

Share your thoughts

Ask anything about this examples