A number equal to sum of the power of 3 of its digits. ( for 3 digit number )
A number equal to sum of the power of 4 of its digits. ( for 4 digit number )
A number equal to sum of the power of n of its digits. ( for n digit number )
Example 1:
153=13 + 53 + 33
153=1 + 125 + 27
So 153 is an Armstrong number
Python Armstrong number within a range or checking user input is Armstrong or not
3 digit Armstrong number
Ask user to enter a 3 digit number and then display if it is an Armstrong number or not.
n=input(" Enter one three digit number ")
my_sum=0
for i in range(0,len(n)):
my_sum=my_sum+pow(int(n[i]),3)
print("Sum of cube of digits : ",my_sum)
if(my_sum==int(n)):
print("This is an Armstrong number : ", n)
else:
print("This is an NOT an Armstrong number : ", n)
By using pow() function we can get the power of two input numbers.
By using len() we can check the number of digits used in the input number ( string data type). Note that all input numbers are string data type by default. We can convert string to integer by suing int() function.
Armstrong number of any number of digits
n=input(" Enter any number more than 9 ")
my_sum=0
k=len(n)
for i in range(0,k):
my_sum=my_sum+pow(int(n[i]),k)
print("Sum of cube of digits : ",my_sum)
if(my_sum==int(n)):
print("This is an Armstrong number : ", n)
else:
print("This is NOT an Armstrong number : ", n)
All Armstrong numbers within a range
List all the Armstrong numbers less than 10000 ( increase the upper limit below )
for n in range(10,10000): # increase this range to get more numbers
my_sum=0
my_str=str(n)
k=len(my_str)
for i in range(0,k):
my_sum=my_sum+pow(int(my_str[i]),k)
#print("Sum of cube of digits : ",my_sum)
if(my_sum==n):
print("This is an Armstrong number : ", n)
Output
This is an Armstrong number : 153
This is an Armstrong number : 370
This is an Armstrong number : 371
This is an Armstrong number : 407
This is an Armstrong number : 1634
This is an Armstrong number : 8208
This is an Armstrong number : 9474