Write a Python function to check if a number is an Armstrong number.
Posted by MaryJns
Last Updated: August 13, 2024
Understanding Armstrong Numbers
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, the number 153 is an Armstrong number because: \[ 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 \]
Python Function to Check Armstrong Numbers
Below is a Python function that checks if a given number is an Armstrong number:
def is_armstrong_number(num):
    # Convert the number to string to easily iterate over digits
    digits = str(num)
    # Calculate the number of digits
    num_digits = len(digits)
    
    # Calculate the sum of each digit raised to the power of num_digits
    armstrong_sum = sum(int(digit) ** num_digits for digit in digits)
    
    # Compare the sum with the original number
    return armstrong_sum == num

# Example usage:
if name == "main":
    number_to_check = 153
    if is_armstrong_number(number_to_check):
        print(f"{number_to_check} is an Armstrong number.")
    else:
        print(f"{number_to_check} is not an Armstrong number.")
How the Function Works
1. Convert to String: The function first converts the number into a string to facilitate the iteration over its digits. 2. Count Digits: It then counts the number of digits in the number, which is necessary for raising each digit to the appropriate power. 3. Calculate Armstrong Sum: Using a generator expression, the function computes the sum of each digit raised to the power of the number of digits. 4. Comparison: Finally, it checks if this sum is equal to the original number and returns the result.
Example
To determine if the number 370 is an Armstrong number:
result = is_armstrong_number(370)
print(result)  # Output: True, since 3^3 + 7^3 + 0^3 = 370
In this implementation, the function efficiently checks any integer for the Armstrong property, making it a useful tool for mathematical explorations in Python.
Related Content
Check Armstrong Number using Python
Check Armstrong Number using Python
gideonna | Apr 13, 2016
C Program to Check Armstrong Number
C Program to Check Armstrong Number
Samath | Jan 02, 2017