Python Check if a Number is an Armstrong Number (Narcissistic Number)

Document 对象参考手册Python3 Examples

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

Code explanation:

  1. num_str = str(num): Convert the input number to a string to calculate its number of digits.
  2. n = len(num_str): Calculate the number of digits of the number.
  3. sum_of_powers = sum(int(digit) ** n for digit in num_str): Calculate the sum of the nth powers of each digit.
  4. 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 数

Document 对象参考手册Python3 Examples

Other extensions