An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the number of digits. For instance, in a 3-digit number like 153, the sum of the cubes of each digit (1^3 + 5^3 + 3^3 = 153) equals the number itself. Thus, 153 is an Armstrong number.
In this article, we will explore a Python program to check whether a number is an Armstrong number. This is a common problem, often seen in computer programming and coding interviews.
To understand and implement this program, you should have a basic understanding of Python programming. Specifically, you should be comfortable with:
- Variables and data types
- Control structures (for loops, if statements)
- User input/output
Our Python program will perform the following steps:
- Ask the user for a number (input).
- Determine the number of digits in the given number.
- Compute the sum of each digit to the power of the number of digits.
- Compare the calculated sum with the original number.
- If they are equal, print that the number is an Armstrong number.
- Otherwise, print that the number is not an Armstrong number.
Here is the Python code that accomplishes this task:
Here’s how the code works:
- The function is_armstrong takes a number as an argument. It converts the number into a string with str(num) to determine the number of digits using the len function.
- It then initializes a variable sum to 0. This variable will hold the sum of each digit to the power of the number of digits.
- The for loop iterates over each digit in the number. It adds the digit (converted back to an integer) raised to the power of the number of digits to sum.
- The function returns True if sum equals the original number (meaning the number is an Armstrong number) and False otherwise.
- The main part of the program asks the user for a number with input. It converts the input to an integer because input returns a string.
- It then calls is_armstrong with the user’s number. If the function returns True, it prints that the number is an Armstrong number. Otherwise, it prints that the number is not an Armstrong number.
Let’s look at a couple of examples to understand the program better:
Explanation: The number 153 has 3 digits. The sum of each digit to the power of 3 is 1^3 + 5^3 + 3^3 = 153, which is equal to the original number.
Explanation: The number 123 also has 3 digits. However, the sum of each digit to the power of 3 is 1^3 + 2^3 + 3^3 = 36, which is not equal to the original number.
In this article, we’ve learned how to create a Python program to check if a number is an Armstrong number. We’ve explored the definition of Armstrong numbers, the prerequisites for understanding the program, and the code implementation with explanations. Finally, we walked through some examples to illustrate how the program works. With this knowledge, you can solve similar problems involving Armstrong numbers and enhance your Python coding skills.