As part of the series to practice python loops, I’ll show you to create a Python program for Armstrong numbers.
Armstrong numbers are those integers numbers that are equal to the sum of each digit to the power of the number of digits in the number.
See the following example.
371 = 33 + 73 + 13 = 27 + 343 + 1
Therefore, 371 is an Armstrong number.
How to check if a number is an Armstrong number
The input is a number. And we also need to know how many digits the number has.
Now, we extract each digit from the number, make a calculation of the digit to the power of the number of digits, and use the basic algorithm for summing to sum all of the calculations.
Python function to check if a number is an Armstrong number
Following the idea above, we write the following Python function.
def armstrong_number(number, number_length):
sum = 0
number_aux = number
while number_aux > 0:
result = number_aux % 10
number_aux = int(number_aux / 10)
sum = sum + pow(result, number_length)
return sum == number
Notice that the digits are extracted from left to right. In this case, it doesn’t matter because we need to sum all of them and a+b=b+a.
The main program you can use to test this is as follows:
if __name__ == "__main__":
n = input('Enter the number: ')
print (armstrong_number(int(n), len(n)))
There is a more pythonic way of implementing the function. However, this implementation will work in other programming languages, you just need to change the syntaxis.
A more pythonic way to check if a number is an Armstrong number
See the code below.
def pythonic_armstrong_number(number):
digits = [int(x) for x in number]
exp = len(number)
result = sum( [ pow(digit,exp) for digit in digits ] )
return result==int(number)
I don’t like this way, because it uses a list, which is unnecessary more memory to solve the problem. Also, it uses a certain type of code very specific to Python.
But feel free to use the one you like the most.
H@ppy coding!
Related posts: