Monday 28 December 2020

Python Program to Check if a Number is an Armstrong Number

 This is a Python Program to check if a number is an Armstrong number.

Problem Description

The program takes a number and checks if it is an Armstrong number.

Problem Solution

1. Take in an integer and store it in a variable.
2. Convert each digit of the number to a string variable and store it in a list.
3. Then cube each of the digits and store it in another list.
4. Find the sum of the cube of digits in the list and check if it is equal to the original number.
5. Print the final result.
6. Exit.

Program/Source Code

Here is source code of the Python Program to check if a number is an Armstrong number. The program output is also shown below.

 
n=int(input("Enter any number: "))
a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
    print("The number is an armstrong number. ")
else:
    print("The number isn't an arsmtrong number. ")
Program Explanation

1. User must enter the number and store it in a variable.
2. The map function obtains each digit from the number and converts it to a string and stores it in a list.
3. The second map function cubes each digit and stores it in another list.
4. Then the sum of the cubes of the digits is found and is checked if it is equal to the original number.
5. If the sum of the cube of digits is equal to the original number, the number is an Armstrong number.
6. The final result is printed.

Runtime Test Cases
 
Case 1:
Enter any number: 13
The number isn't an arsmtrong number. 
 
Case 2:
Enter any number: 371
The number is an armstrong number.

No comments:

Post a Comment