Example HTML page

A Python program to check Armstrong number.

Armstrong number: The number is said to be an Armstrong number if the sum of the cubes of each digits is equal to the number itself.

Ex: 407 = Sum of its cubes =4**3+0**3+7**3=407.It is an Armstrong number.

704 = Sum of its cubes = 7**3+0**3+4**3 = 407.So it is not an Armstrong number.

#To check Armstrong number for 3 digits.

num = int(input("Enter a number: "))
sum = 0
x = num
while x > 0:
   digit = x % 10
   sum += digit ** 3
   x //= 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

Enter a number: 351

351 is not an Armstrong number

Explanation:

Initially, we take input from the user and to check that input number is an Armstrong number or  not we initialize ‘sum’ value to zero and obtain every digit  number by using ‘%(modulo)’ operator. When that number is dividing by 10 then the remainder of a number is the last digit of that number. The cubes of those digits are evaluated by using ‘exponent(*)’ operator. Using ‘if-else’ condition we compare the sum with the actual number. If they are equal, then we confirm that it is an Armstrong number.

#To check Armstrong number of n digits.

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

Output

Enter a number: 1634

1634 is an Armstrong number

Enter a number: 54748

54748 is an Armstrong number

 

Enter a number: 12345654

12345654 is not an Armstrong number

#To print the Armstrong number between a specified range.

L = int(input("Enter lower limit: "))
U = int(input("Enter upper limit: "))
for num in range(L, U + 1):
   seq = len(str(num))
   sum = 0
   a = num
   while a > 0:
       digit = a % 10
       sum += digit ** seq
       a //= 10
   if num == sum:
       print(num)

Output

Enter lower limit: 1234

Enter upper limit: 12345

1634

8208

9474

 

Enter lower limit: 100

Enter upper limit: 200

153

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest