📜  armstrong number (1)

📅  最后修改于: 2023-12-03 15:13:29.099000             🧑  作者: Mango

Armstrong Number

An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in the number itself.

In other words, an Armstrong number is such that if we take each digit of the number, raise it to the power of the number of digits in the number, and then sum them up, we get the original number back.

For example, 153 is an Armstrong number because:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Armstrong numbers are also known as Narcissistic numbers or Plus Perfect numbers.

Algorithm

To determine if a given number is an Armstrong number, we can follow these steps:

  1. Count the number of digits in the given number.
  2. Initialize a variable sum to 0.
  3. Extract each digit from the number using modulo and division operations.
  4. Raise each digit to the power of the number of digits and add it to sum.
  5. Check if the computed sum is equal to the original number.
Code Example

Here's an example of a method that checks if a given number is an Armstrong number:

def is_armstrong_number(num):
    # Count the number of digits
    num_of_digits = len(str(num))

    # Initialize sum
    armstrong_sum = 0
    
    # Use a temporary variable to store the original number
    temp = num

    # Calculate the sum of digits raised to the power of the number of digits
    while temp > 0:
        digit = temp % 10
        armstrong_sum += digit ** num_of_digits
        temp //= 10

    # Check if the sum is equal to the original number
    if armstrong_sum == num:
        return True
    else:
        return False

You can use this method to check if a number is an Armstrong number. For example:

num = 153
if is_armstrong_number(num):
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")

This will output:

153 is an Armstrong number

Feel free to use this code snippet to check Armstrong numbers in your programming projects.