Armstrong Number in Python: Armstrong Number is an integer such that the sum of the cubes of its digits is equal to the number itself. Armstrong numbers are 0, 1, 153, 370, 371, 407, etc.
Formula to calculate Armstrong Number:
wxyz = pow(w,n) + pow(x,n) + pow(y,n) + pow(z,n)
Example 1:
Let’s look at 153 as an example to understand why it’s an Armstrong number.
153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
Example 2:
Let’s look at 13 as an example to understand whether it’s an Armstrong number or not.
13 = 1*1 + 3*3 = 1 + 9 = 10
Here, since 10 is not equal to 13, we can conclude that 13 is not an Armstrong number.
Write a Python Program to check if a number is an Armstrong number. If the number is an Armstrong then display “it is an Armstrong number” else display “it is not an Armstrong number”.
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.
Here is the source code of the Python Program to Check If a Given Number is ArmStrong Number. The Python program is successfully compiled and run on a Windows system. The program output is also shown below.
# Armstrong Number Program in Python 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 is not an arsmtrong number. ")
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.
Time Complexity: O(log n)
The time complexity of the armstrong number program is O(log n) as it iterates over the digits of the input number.
Space Complexity: O(log n)
The space complexity is also O(log n) because it creates lists for storing the digits and their cubes, with the size proportional to the number of digits in the input number.
Testcase 1: In this case, we enter the number “13” as input to check whether it is a arsmtrong number or not.
Enter any number: 13 The number is not an arsmtrong number.
Testcase 2: In this case, we enter the number “153” as input to check whether it is a arsmtrong number or not.
Enter any number: 371 The number is an armstrong number.
To practice programs on every topic in Python, please visit “Programming Examples in Python”.
- Check Information Technology Books
- Apply for Python Internship
- Practice Programming MCQs
- Apply for Programming Internship
- Check Python Books