Armstrong number
An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because:
1^3 + 5^3 + 3^3 = 153
Other Armstrong numbers include 371, 407, and 1634.
To check if a number is an Armstrong number, you can use the following algorithm:
- Calculate the number of digits in the number.
- For each digit in the number, raise it to the power of the number of digits and add it to a running total.
- If the running total is equal to the original number, the number is an Armstrong number.
For example, to check if 371 is an Armstrong number:
- The number of digits in 371 is 3.
- 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371.
- The running total is equal to the original number, so 371 is an Armstrong number.
I hope this helps! Let me know if you have any other questions.
Here is some sample Python code that checks if a number is an Armstrong number:
Program:
def is_armstrong_number(num): # convert the number to a string and get the number of digits num_str = str(num) num_digits = len(num_str) # initialize a variable to store the sum of the digits raised to the power of the number of digits sum = 0
# iterate through each digit in the number
for digit in num_str:
# raise the digit to the power of the number of digits and add it to the sum
sum += int(digit) ** num_digits
# return True if the sum is equal to the original number, False otherwise
return sum == num
# test the function
print(is_armstrong_number(153)) # should print True
print(is_armstrong_number(371)) # should print True
print(is_armstrong_number(123)) # should print False
This code defines a function is_armstrong_number() that takes a number as a parameter and returns True if the number is an Armstrong number, or False otherwise. The function first converts the number to a string and counts the number of digits. It then iterates through each digit in the number, raising it to the power of the number of digits and adding it to a sum. Finally, it checks if the sum is equal to the original number and returns the result.
Comments