Python Program to find if a number is Armstrong or not

Find if a number is Armstrong or not using python :

A three digit number is called a Armstrong number if the sum of cube of its digits is equal to the number itself.

407 is an Armstrong number since 4**3 + 0**3 + 7**3 = 407

For a number with ‘n’ digits, the power value should be n, not 3. i.e. for a 4 digit number 1234 , we should check for 1**4 + 2**4 + 3**4 + 4**4 .
To check if a number is Armstrong or not in python, we can take any positive number as input from the user. Then, we will check the count of the digits by converting it to a string and using len() method on the string.

Find Armstrong or not from user input :

def findArmStrongSum(no):
    currentNo = no
    length = len(str(currentNo))
    sum = 0

    while currentNo > 0:
        lastDigit = currentNo % 10
        sum += lastDigit ** length

        currentNo = int(currentNo/10)

    return sum

no = int(input("Enter a positive number :"))

if(no>0):
    armStrongSum = findArmStrongSum(no)
    if(armStrongSum == no):
        print ("Given number is an Armstrong Number")
    else:
        print ("Number is not an Armstrong Number”)
else:
    print ("Please enter a valid number")

Examples :

Enter a positive number :420
72
Number is not an Armstrong Number

Enter a positive number :407
407
Given number is an Armstrong Number

Find out all Armstrong Numbers in a range :

def findArmStrongSum(no):
    currentNo = no
    length = len(str(currentNo))
    sum = 0

    while currentNo > 0:
        lastDigit = currentNo % 10
        sum += lastDigit ** length

        currentNo = int(currentNo/10)

    return sum


strongNumList = []

for i in range(0,1000):
    armStrongSum = findArmStrongSum(i)
    if (armStrongSum == i):
        strongNumList.append(i)

for no in strongNumList :
    print (no)

Output :

0
1
2
3
4
5
6
7
8
9
153
370
371
407

Leave a Reply