December 30, 2024
An Armstrong number (also called a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
The concept is based on the number of digits in the number. For example, if the number has n
digits, the sum of each digit raised to the power of n
should be equal to the original number for it to be classified as an Armstrong number.
n
(where n
is the number of digits).Let’s take the number 153:
n
).n
.
def is_armstrong(num):
# Step 1: Convert number to string to get each digit
digits = str(num) # This turns the number into a string, e.g., '153'
# Step 2: Find the number of digits (n)
n = len(digits) # For 153, n will be 3
# Step 3: Calculate the sum of digits raised to the power n
sum_of_powers = sum(int(digit) ** n for digit in digits)
# Step 4: Compare the sum to the original number
return sum_of_powers == num # If sum equals original, return True, else False
# Step 5: Ask the user for input
number = int(input("Enter a number: "))
# Step 6: Check if the number is an Armstrong number
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
str(num)
:
num = 153
, then digits = '153'
.n = len(digits)
:
n = 3
.sum(int(digit) ** n for digit in digits)
:
digits
.int(digit)
), then raises it to the power of n
.1^3 = 1
5^3 = 125
3^3 = 27
sum_of_powers = 1 + 125 + 27 = 153
sum_of_powers == num
:
True
, meaning it’s an Armstrong number.False
.n = 3
(because 153 has 3 digits)n = 4
(because 9474 has 4 digits)n = 3
(because 123 has 3 digits)