Search code examples
pythonmathlogic

Python: Find the numbers for which the sum of the digits raised by the power of the number of digits in a number is equal to the number itself


Find the numbers for which the sum of the digits raised by the power of the number of digits in a number is equal to the number itself.

For example

 2^1 = 2
 1^3 + 5^3 + 3^3 = 153
 3^3 + 7^3 + 0^3 = 370
 1^4 + 6^4 + 3^4 + 4^4 = 1634

Wrote the following code:

armstrong_num=[]
for i in range(0, 10000):
    n=len(i)
    total=0
    for j in i:
        total = total+(j)**n
        if total==int(i):
            armstrong_num.append()
print(armstrong_num)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '153', '370', '370', '371', '407', '1634', '6688', '8208', '9474']

It works fine except one problem. The number 370 is identified twice. Any hint to correct the code.


Solution

  • The code below accounts for a few of the comments left on your post. ** Updated accounting for @Mark's comment posted below.

    armstrong_num=[]
    for i in range(0, 10000):
        n=len(str(i))
        total=0
        for char in str(i):
            total = total+(int(char))**n
        if total==int(i):
           armstrong_num.append(i)
    print(armstrong_num)