A number with the below property is called Armstrong number of order N. Where the sum of the power of each digit with the number of its digits.
abcd...(n digits) = a^n + b^n + c^n + ...
For example, Armstrong number of order 3 is a number in which the sum of cubes (power of 3) of its digits is equal to the number itself. Let us take an example Armstrong number check the sum of cubes of its digits.
# Example 407 = 4*4*4 + 0*0*0 + 7*7*7 407 = 64 + 0 + 343 So, 407 is an Armstrong number of order 3.
Python program to find given number is Armstrong number or not (nth order)
# armstrongnum.py # Function to find given number is armstrong or not. def isArmstrong(num): order = len(str(num)) sum = 0 curr = num while(curr): digit = curr % 10 curr = curr / 10 sum += digit ** order if sum == num: return True return False # checks if 153 is armstrong number or not. print(isArmstrong(153)) # checks if 256 is armstrong number or not. print(isArmstrong(256))
The above example takes the order of the number first and calculates its armstrong number with that and returns True if the sum equals to the given input.
# Output $python armstrongnum.py True False
Now, we use the same above function and find all armstrong numbers below 1000 using below python program.
Python program to list all armstrong numbers less than given number
# listarmstrongnums.py # Function to find given number is armstrong or not. def isArmstrong(num): order = len(str(num)) sum = 0 curr = num while(curr): digit = curr % 10 curr = curr / 10 sum += digit ** order if sum == num: return True return False # prints all armstrongs less than given numbers. def listArmstrongs(num): for val in range(1, num): if isArmstrong(val): print(val) # lists all armstrong numbers below 1000. listArmstrongs(1000)
Above code lists all armstrong numbers with different ordres 1, 2 and 3rd order armstrong numbers. Below is the output of the program.
# Output $ python listarmstrongnums.py 1 2 3 4 5 6 7 8 9 153 370 371 407
Overall, above are the two functions which combined gives us list of all armstrong numbers less than the input (i.e., 1000).
With this we hope you get all information about armstrong numbers and their related python programs. Keep learning!!.