Python: Check if a Number is an Armstrong Number
An Armstrong number (Narcissistic number) is an n-digit number whose sum of each digit raised to the power of n equals itself. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
The following is a Python program for checking whether a number is an Armstrong number:
Example
def is_narcissistic_number(num):
# Convert the number to a string for easy digit-by-digit processing
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of each digit raised to the power of n
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check whether it equals the original number
return sum_of_powers == num
# Test
number = 153
if is_narcissistic_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
# Convert the number to a string for easy digit-by-digit processing
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of each digit raised to the power of n
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check whether it equals the original number
return sum_of_powers == num
# Test
number = 153
if is_narcissistic_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
Code Explanation:
is_narcissistic_numberThe function accepts an integernumas a parameter.num_str = str(num)Convert the integer to a string for digit-by-digit processing.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 each digit raised to the power of n.return sum_of_powers == numCheck whether the calculated sum equals the original number; if equal, returnTrue, otherwise returnFalse。- In the test section, we test the number 153 and output the result.
Output Result:
153 是水仙花数Other Extensions
Python3 Examples