Armstrong Numbers in Python

What are Armstrong Numbers?

Armstrong numbers are integers where the sum of each digit raised to the power of the number of digits is equal to the original number.

Example

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

Python Function

def is_armstrong(num): original = num sum = 0 while num > 0: digit = num % 10 sum += digit ** len(str(original)) num //= 10 return sum == original

Explanation

1. We define a function is_armstrong that takes a number as input. 2. We store the original number and initialize a sum variable. 3. We loop while the number is greater than 0. 4. Inside the loop, we extract the last digit and add its power to the sum.

Usage

number = 153 if is_armstrong(number): print(number, "is an Armstrong number") else: print(number, "is not an Armstrong number")