Write a Python program to check whether a given number is an Armstrong number or not.
An Armstrong number (also known as a Narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Input-Output Examples
plaintext
Example 1:
Input: Enter a number: 153
Output: 153 is an Armstrong number.
Example 2:
Input: Enter a number: 123
Output: 123 is not an Armstrong number.
Algorithm to check whether a number is Armstrong number or not
- Start
- Take input: Prompt the user to enter a number.
- Calculate the number of digits: Determine how many digits the number has.
- Compute the sum of the digits raised to the power of the number of digits:
- Extract each digit of the number.
- Raise each digit to the power of the total number of digits and sum them.
- Check if the sum equals the original number:
- If yes, it is an Armstrong number.
- If no, it is not an Armstrong number.
- Display the result.
- End
Python Program to check whether a number is Armstrong number or not
python
# Python program to check if a number is an Armstrong number
# Take input from the user
num = int(input("Enter a number: "))
# Calculate the number of digits in the number
num_digits = len(str(num))
# Initialize the sum variable to 0
sum_of_powers = 0
# Create a temporary variable to hold the value of num
temp = num
# Compute the sum of the digits raised to the power of the number of digits
while temp > 0:
digit = temp % 10 # Extract the last digit
sum_of_powers += digit ** num_digits # Raise the digit to the power and add it to the sum
temp //= 10 # Remove the last digit from temp
# Check if the sum is equal to the original number
if num == sum_of_powers:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Code Explanation
- Taking input from the user:
The program uses theinput()
function to take a number from the user, which is then converted to an integer usingint()
. - Calculating the number of digits:
Thelen(str(num))
function is used to determine how many digits the number has. This is necessary because each digit of the number needs to be raised to the power of the number of digits. - Summing the digits raised to the power of the number of digits:
The program uses awhile
loop to extract each digit of the number. For each extracted digit, it raises the digit to the power of the total number of digits and adds it tosum_of_powers
. The last digit is removed from the temporary variabletemp
after each iteration. - Checking if the sum equals the original number:
If the sum of the digits raised to the power is equal to the original number, the number is an Armstrong number. If not, it is not an Armstrong number. - Displaying the output:
Theprint()
function displays whether the number is an Armstrong number or not, using an f-string to format the result.