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 :
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