Python Program to Check Armstrong Number


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

An Armstrong number, is a number that is equal to the sum of its own digits raised to the power of the number of digits in the number. In other words, an n-digit number is an Armstrong number if the sum of its digits raised to the power of n is equal to the original number.

For example, the number 153 is an Armstrong number because it is a 3-digit number and:

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

Similarly, 1634 is an Armstrong number because it is a 4-digit number and:

1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634


Python Code :

The below Python program to check if a given number is an Armstrong number or not:


# Function to check Armstrong number
def is_armstrong(num):
    # Convert number to string to count number of digits
    num_str = str(num)
    # Count number of digits
    num_digits = len(num_str)
    # Calculate sum of cubes of each digit
    armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)
    # Check if sum is equal to original number
    return armstrong_sum == num

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

In the above code, the is_armstrong function takes a number as input and returns True if it is an Armstrong number, and False otherwise. To check if a number is an Armstrong number, we first count the number of digits in the number, and then compute the sum of cubes of each digit. If the resulting sum is equal to the original number, then it is an Armstrong number.

We then use this function to check if a given number (in this case, 153) is an Armstrong number. If it is, we print a message indicating so, and if it’s not, we print a different message.

For example :


153 is an Armstrong number


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co