Python Check if a Number is an Armstrong Number (Narcissistic Number)
An Armstrong number (narcissistic number) is an n-digit number where the sum of the nth powers of its digits equals the number itself. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
Example
def is_armstrong_number(num):
# Convert the number to a string to easily calculate the number of digits
num_str = str(num)
n = len(num_str)
# Calculate the sum of the nth powers of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if it is an Armstrong 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 easily calculate the number of digits
num_str = str(num)
n = len(num_str)
# Calculate the sum of the nth powers of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if it is an Armstrong 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): Convert the input number to a string to calculate its number of digits.n = len(num_str): Calculate the number of digits of the number.sum_of_powers = sum(int(digit) ** n for digit in num_str): Calculate the sum of the nth powers of each digit.return sum_of_powers == num: Check whether the calculated sum equals the original number. If so, return True; otherwise, return False.
Output result:
153 是一个 Armstrong 数Other extensions
Python3 Examples