Data SciencePython

Arunav Goswami

Data Science Consultant at almaBetter

Learn about Armstrong numbers in Python with for loop, while loop, and function examples. Explore how to code Armstrong numbers effectively in this lesson

An Armstrong number, also known as a *narcissistic* number, is a number that is equal to the sum of its digits raised to the power of the number of digits. This article will explore the concept of Armstrong numbers, how to identify them, and provide various Python implementations using loops and functions.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number because:

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

This concept can be generalized for any number of digits. For an n-digit number, the number is considered an Armstrong number if the sum of its digits each raised to the power of n equals the original number.

Armstrong numbers can exist for any number of digits. Here are some examples of n-digit Armstrong numbers:

**1-Digit Armstrong Numbers**:- All single-digit numbers (0–9) are Armstrong numbers because each number is equal to itself raised to the power of one.
- Examples: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

**2-Digit Armstrong Numbers**:- There are no 2-digit Armstrong numbers, as no two-digit number equals the sum of its digits each raised to the power of 2.

**3-Digit Armstrong Numbers**:- Examples:

```
153: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
370: 3³ + 7³ + 0³ = 27 + 343 + 0 = 370
371: 3³ + 7³ + 1³ = 27 + 343 + 1 = 371
407: 4³ + 0³ + 7³ = 64 + 0 + 343 = 407
```

**4-Digit Armstrong Numbers**:- Examples:

```
1634: 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634
8208: 8⁴ + 2⁴ + 0⁴ + 8⁴ = 4096 + 16 + 0 + 4096 = 8208
9474: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474
```

**5-Digit Armstrong Numbers**:- Examples:

```
54748: 5⁵ + 4⁵ + 7⁵ + 4⁵ + 8⁵ = 3125 + 1024 + 16807 + 1024 + 32768 = 54748
92727: 9⁵ + 2⁵ + 7⁵ + 2⁵ + 7⁵ = 59049 + 32 + 16807 + 32 + 16807 = 92727
93084: 9⁵ + 3⁵ + 0⁵ + 8⁵ + 4⁵ = 59049 + 243 + 0 + 32768 + 1024 = 93084
```

**6-Digit Armstrong Numbers**:- Example:

```
548834: 5⁶ + 4⁶ + 8⁶ + 8⁶ + 3⁶ + 4⁶ = 15625 + 4096 + 262144 + 262144 + 729 + 4096 = 548834
```

These examples illustrate how Armstrong numbers exist for different digit lengths, with each number matching the sum of its digits raised to the appropriate power.

To find Armstrong numbers in Python, the primary steps are:

- Extract digits of the number.
- Raise each digit to the power of the number of digits.
- Sum these powered values.
- Check if the sum equals the original number.

Here, we will implement different methods to check Armstrong numbers using loops and functions.

This approach uses a for loop to iterate through the digits of a number and calculate whether it is an Armstrong number.

```
# Python program to check Armstrong number using for loop
# Input number
num = int(input("Enter a number: "))
# Convert number to string to easily iterate through each digit
num_str = str(num)
# Calculate the length of the number (number of digits)
n = len(num_str)
# Initialize sum
armstrong_sum = 0
# Loop through each digit
for digit in num_str:
# Add the nth power of each digit to the sum
armstrong_sum += int(digit) ** n
# Check if the calculated sum matches the original number
if armstrong_sum == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
```

**Explanation:**

- The number is converted to a string to easily iterate over each digit.
- Each digit is raised to the power equal to the total number of digits.
- If the calculated sum matches the original number, it is an Armstrong number.

A while loop can also be used to perform the same operation. This approach demonstrates a different way of extracting digits.

```
# Armstrong number program in python using while loop
# Input number
num = int(input("Enter a number: "))
# Make a copy of the number for comparison later
temp = num
# Initialize sum
armstrong_sum = 0
# Find the number of digits
n = len(str(num))
# Loop until all digits are processed
while temp > 0:
# Get the last digit
digit = temp % 10
# Add the nth power of the digit to the sum
armstrong_sum += digit ** n
# Remove the last digit from temp
temp //= 10
# Check if the calculated sum matches the original number
if armstrong_sum == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
```

**Explanation:**

- This program uses modulo and integer division to extract digits from the number.
- The loop continues until all digits are processed.
- The process of checking the Armstrong number is the same.

Creating a function in Python makes the code reusable and more organized.

```
# Function to check if a number is an Armstrong number
def is_armstrong(num):
# Convert number to string to calculate the number of digits
n = len(str(num))
# Initialize sum
armstrong_sum = 0
# Temporary variable to manipulate the number
temp = num
while temp > 0:
digit = temp % 10
armstrong_sum += digit ** n
temp //= 10
# Return True if sum equals the original number
return armstrong_sum == num
# Input number
number = int(input("Enter a number: "))
# Check and display result
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
```

**Explanation:**

- This function is_armstrong() performs the Armstrong check and returns a Boolean value.
- The function approach enhances code readability and reusability.

Often, the task is to find all Armstrong numbers within a specified range. Below is a code snippet demonstrating this.

```
# Python Program for Armstrong Number within a range
# Input range
lower = int(input("Enter the lower range: "))
upper = int(input("Enter the upper range: "))
# Loop through the range
for num in range(lower, upper + 1):
# Calculate the number of digits
n = len(str(num))
# Initialize sum
armstrong_sum = 0
# Copy of the number
temp = num
while temp > 0:
digit = temp % 10
armstrong_sum += digit ** n
temp //= 10
# Print the number if it is an Armstrong number
if num == armstrong_sum:
print(num)
```

**Explanation:**

- The program takes a range as input and checks each number within the range.
- The Armstrong check is performed similarly using loops.

*Boost your coding skills with our* *online Python compiler**, explore in-depth* *Python tutorials**, and get our handy* *Python cheat sheet**!*

Armstrong numbers, though primarily a mathematical curiosity, have several educational and computational applications:

**Cryptography and Digital Security**:

- Concepts similar to Armstrong numbers are used in hashing functions and data integrity checks.

**Number Theory Research**:

- Studied in mathematical research to explore properties of special numbers.
- Used in exploring base representation studies in different numeral systems.

**Game Development and Puzzle Design**:

- Used in math-based games and puzzles to challenge logic and numerical understanding.

**Benchmarking and Testing**:

- Used in software development for testing algorithm performance and optimization.

**Digital Art and Recreational Mathematics**:

- Featured in artistic representations and recreational mathematics for visual patterns.

These applications highlight Armstrong numbers as useful in educational and computational contexts, offering valuable insights into number theory and programming.

Armstrong numbers are an interesting concept in number theory and can be easily implemented in Python using different approaches. Whether using loops or functions, checking if a number is an Armstrong number involves straightforward calculations of powers and sums. Mastering this concept provides a deeper understanding of Python’s numerical operations and control structures.

Enroll in our Data Science course today and take the first step toward earning your Masters in Data Science!

Related Articles

Top Tutorials

- Policies
- Privacy Statement
- Terms of Use

- Contact Us
- admissions@almabetter.com
- 08046008400

- Official Address
- 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025

- Communication Address

- Follow Us

© 2024 AlmaBetter