Python Check if a Number is an Armstrong Number
An Armstrong number (also known as a narcissistic number) is an n-digit number where the sum of the n-th powers of its digits equals the number itself. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
The following is a Python program to determine whether a number is an Armstrong number.
Example
def is_armstrong_number(num):
# Convert the number to a string to get each digit individually
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of the n-th power of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if the sum equals the original number
return sum_of_powers == num
# Test
number = 153
if is_armstrong_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
# Convert the number to a string to get each digit individually
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of the n-th power of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if the sum equals the original number
return sum_of_powers == num
# Test
number = 153
if is_armstrong_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
Code Explanation:
num_str = str(num): Converts the input number to a string, so that each digit can be obtained individually.n = len(num_str): Get the number of digits.sum_of_powers = sum(int(digit) ** n for digit in num_str): Calculate the sum of the n-th powers of each digit. Here, a list comprehension is used to iterate over each digit, convert it to an integer, perform the exponentiation, and finally usesum()the function to sum.return sum_of_powers == num: Check whether the calculated sum equals the original number; if it is equal, returnTrue, otherwise returnFalse。
Output Result:
153 是一个 Armstrong 数Other Extensions
Python3 Examples