Python Program to check Armstrong Number

1. Introduction

An Armstrong number (also known as a narcissistic number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. These numbers are special in mathematics and programming, and checking for them is a common problem in coding exercises. This blog post will guide you through creating a Python program to check if a given number is an Armstrong number.

2. Program Steps

1. Prompt the user to enter a number.

2. Calculate the number of digits in the given number.

3. Sum the powers of each digit according to the number of digits.

4. Check if the sum is equal to the original number.

5. Display whether the entered number is an Armstrong number or not.

3. Code Program

# Step 1: Prompt the user to input a number
num = int(input("Enter a number: "))

# Step 2: Calculate the number of digits
num_of_digits = len(str(num))

# Step 3: Sum the powers of each digit
sum_of_powers = sum([int(digit) ** num_of_digits for digit in str(num)])

# Step 4: Check if the sum is equal to the original number
if sum_of_powers == num:
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

Output:

Enter a number: 153
153 is an Armstrong number.

Explanation:

1. The user is prompted to enter a number, which is stored as an integer.

2. The program calculates the number of digits in the entered number by converting the number to a string and then using the len function.

3. It then calculates the sum of each digit raised to the power of the number of digits in the number. This is achieved by iterating over each digit in the string representation of the number, converting each digit back to an integer, raising it to the power of the number of digits, and summing these values.

4. The program checks if this sum is equal to the original number. If it is, the number is an Armstrong number; otherwise, it is not.

5. Finally, the program prints the result, indicating whether the entered number is an Armstrong number or not.


Comments