Table of Contents
What is Armstrong number in python ?
An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits. Let’s write a Python program to check if a given number is an Armstrong number or not, and I’ll provide a stepwise algorithm along with it.
Stepwise algorithm to check Armstrong number:
- Start by taking input from the user for the number to be checked.
- Calculate the total number of digits in the given number. You can achieve this by converting the number to a string and then using the len()
- Initialize a variable sum to 0. This variable will store the sum of the digits raised to the power of the number of digits.
- Iterate through each digit in the number.
- For each digit, raise it to the power of the total number of digits and add it to the sum
- After iterating through all the digits, check if the calculated sum is equal to the original number.
- If the sum is equal to the original number, then it is an Armstrong number. Otherwise, it is not.
- Print the result accordingly.
To determine if a Armstrong Number program in Python, you can use the following code:
# Step 1: Take input from the user
number = int(input("Enter a number: "))
# Step 2: Calculate the number of digits
num_digits = len(str(number))
# Step 3: Initialize sum variable
sum = 0
# Step 4: Iterate through each digit
temp = number
while temp > 0:
digit = temp % 10
# Step 5: Calculate sum of digits raised to the power of num_digits
sum += digit ** num_digits
temp //= 10
# Step 6: Check if sum is equal to the original number
if sum == number:
print(number, "is an Armstrong number.")
else:
print(number, "is not an Armstrong number.")
Input:
Enter the number:153
Output:
153 is an Armstrong Number