Python: Check if a Number is an Armstrong Number

Document 对象参考手册Python3 Examples

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")

Code Explanation:

  1. is_narcissistic_numberThe function accepts an integernumas a parameter.
  2. num_str = str(num)Convert the integer to a string for digit-by-digit processing.
  3. n = len(num_str)Get the number of digits.
  4. sum_of_powers = sum(int(digit) ** n for digit in num_str)Calculate the sum of each digit raised to the power of n.
  5. return sum_of_powers == numCheck whether the calculated sum equals the original number; if equal, returnTrue, otherwise returnFalse。
  6. In the test section, we test the number 153 and output the result.

Output Result:

153 是水仙花数

Document 对象参考手册Python3 Examples

Other Extensions