Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this Python Program is not printing remaining armstrong number till 10000? It is only printing up to 407

I am new to python and below is my code it is printing only 1, 153, 370, 371 and 407.

def checkArmStrong(num):
    sum = 0
    temp = num
    while temp > 0:
        rem = temp % 10
        sum += rem ** 3
        temp //= 10
    return sum == num


for x in range(1, 10000):
    if checkArmStrong(x):
        print(x)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to adjust the power in your calculation, right now it’s always 3, which works for three-digit numbers but is not correct for numbers with more/less digits.

An Armstrong number is a number that equals the sum of its digits, each raised to the power of the number of digits. So for a 2 digit number the power needs to be 2, then 3 for a 3 digit number and so on.

You can fix your calculation like this:

def checkArmStrong(num):
    sum = 0
    temp = num
    num_digits = len(str(num))
    while temp > 0:
        rem = temp % 10
        sum += rem ** num_digits
        temp //= 10
    return sum == num
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading