Program of Armstrong Number in Python

Armstrong Number

This post explains how we can check any number entered by the user is an Armstrong or not using python language. Four different programs in python language are given with their code and output image.

What is meant by Armstrong Number?

The number that is the sum of its own digits in which each raised to the power of the number of digits.

abcd…n = a^n + b^n + c^n + d^n + …

Example:

Example 1:
153 = 111 + 555 + 333 // 153 is an Armstrong.
Example 2:
Input : 1251
Output : No
1253 is not a Armstrong
1111 + 2222 + 5555 + 1111 = 643

3-Digit Armstrong Program in Python:

The following code helps the user to check any 3-digit entered by the is Armstrong or not.

Code:

num = int(input("Enter 3 digit number: "))
print("\n")
sum = 0

# find sum of the cube of each digit

temp = num
while temp > 0:
    dig = temp % 10
    sum = sum + (dig ** 3)
    temp = temp // 10

if num == sum:
    print('{} is an Armstrong number'.format(num))
else:
    print('{} is not an Armstrong number'.format(num))

Output:

3-digit Armstrong

Write a Program to Find All Armstrong Number In given Range Using Python

The following code gives all the Armstrong numbers in the range entered by the user.

Code:

a_lower = int(input("Enter lower range: "))
b_upper = int(input("Enter upper range: "))

for num in range(a_lower, b_upper + 1):

   p = len(str(num))
   sum = 0
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit **p
       temp //= 10

   if num == sum:
       print(num)

Output:

Given range

Armstrong Program in Python Using List Compression:

The following code gives the Armstrong numbers in the range specified by the coder using lit compression in python:

Code :

print("Armstrong Number:")
x = [a for a in range (10000) if sum (list(map(lambda b:b ** len (str (a)),list (map(int,str(a))))))==a]
print(x) 

Output:

List Compression

Armstrong Number in Python Using While Loop

Following Code check whether the number is Armstrong number or not using a while loop in python for n-digit number.

Code:

num = int(input("Enter the number: "))
# find out number of digits the input number has
p = len(str(num))
sum = 0
temp = num
while temp > 0:

    dig = temp % 10
    # find out power of each digit while adding
    sum = sum + (dig ** p)
    temp = temp // 10
if num == sum:
    print('{} is an Armstrong number'.format(num))
else:
    print('{} is not an Armstrong number'.format(num))

Output:

While Loop

Discover more from easytechnotes

Subscribe to get the latest posts sent to your email.

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scroll to Top