Home > Software design >  Made a program to check armstrong number, but can't find out what's wrong with it
Made a program to check armstrong number, but can't find out what's wrong with it

Time:12-31

This is basically code to check whether the given number is an armstrong number.But I just don't understand why my output does'nt come correctly

num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum  = digit * 3
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

The output isn't coming correctly

CodePudding user response:

Get the total number of digits and apply the pow() function

num = int(input("Enter a number: "))
num_digits = len(str(num))
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum  = pow(digit, num_digits)
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

CodePudding user response:

Your algorithm is wrong. The line:

sum  = digit * 3

...should be...

sum  = digit ** 3

That was clearly your intent. However, that only works for 3-digit numbers. A general approach could be implemented thus:

from math import log10

def isArmstrong(n):
    _len = int(log10(n))   1
    _n = n
    _sum = 0
    while (_n > 0):
        _sum  = (_n % 10) ** _len
        _n //= 10
    return _sum == n

Example:

# all values from 1-9 are Armstrong numbers so start from 10
for i in range(10, 1_000_000):
    if isArmstrong(i):
        print(i)

Output:

153
370
371
407
1634
8208
9474
54748
92727
93084
548834
  • Related