To check if a given number is an Armstrong number, you can follow these steps to write a Python program:
- Get the input number from the user.
- Convert the input number to a string to iterate over its digits.
- Calculate the number of digits in the input number using the
len()
function. - Initialize a variable
armstrong_sum
to 0. This variable will store the sum of the individual digits raised to the power of the number of digits. - Iterate over each digit of the input number using a
for
loop. - Convert each digit from string to an integer using the
int()
function. - Raise each digit to the power of the number of digits and add the result to the
armstrong_sum
variable. - After the loop, check if the
armstrong_sum
is equal to the original input number. - If the
armstrong_sum
is equal to the input number, print that the number is an Armstrong number. Otherwise, print that it is not.
Here’s the complete code for the program:
# Step 1: Get input number from the user
num = int(input("Enter a number: "))
# Step 2: Convert the number to a string
num_str = str(num)
# Step 3: Calculate the number of digits
num_digits = len(num_str)
# Step 4: Initialize the armstrong sum
armstrong_sum = 0
# Step 5: Iterate over each digit
for digit in num_str:
# Step 6: Convert digit from string to integer
digit_int = int(digit)
# Step 7: Calculate the sum of digits raised to the power of the number of digits
armstrong_sum += digit_int ** num_digits
# Step 8: Check if the sum is equal to the original number
if armstrong_sum == num:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")
Now you can run the program, enter a number, and it will tell you whether the number is an Armstrong number or not.
+ There are no comments
Add yours