Saturday, 16 September 2017

check whether given number is Armstrong or not


Armstrong number: the sum of cubes of each digit in a number is equal to original number.

Example:
                     153=13 + 53 + 33
                                   1 +  125 + 27



Example:

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")

Output:

enter a number: 153

153 is an Armstrong number

Example 2: 
find the Armstrong numbers between given range

lower = 100
upper = 2000
for num in range(lower, upper + 1):  
   order = len(str(num))   
   sum = 0   
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10
   if num == sum:

       print(num)

Output:

153
370
371
407
1634

No comments:

Post a Comment