Armstrong Number Program in Python: Easy Code with Explanation

An Armstrong number is a unique number that is equivalent to the total of its digits, each of which is raised to the power of its number of digits. Understanding this concept is a great way to practice programming fundamentals like loops, conditionals, and mathematical operations. This comprehensive guide explores how to write an Armstrong number program in Python that checks whether a given number is an Armstrong number using multiple approaches.

Article Information:

Table of Contents

What is an Armstrong number?

An Armstrong number, also called a Narcissistic number or Pluperfect Digital Invariant (PPDI), is a number that equals the sum of its digits, with each digit raised to the power of the total number of digits. These numbers are interesting in mathematics and are used in Python programming to practice loops, recursion, and mathematical operations.

Formula

For an n-digit number, an Armstrong number follows this rule:

d1^n + d2^n + ⋯ + dm^n = original number

Where:

Example of an Armstrong Number

Take 153 as an example:

Algorithm to Check if the Given Number is Armstrong or Not

  1. Input the number that needs to be checked
  2. Store the original number in a variable for later comparison
  3. Count the total number of digits in the number
  4. Assign a variable to sum each digit, exponentiated to the power of the number of digits
  5. Loop through each digit of the number:
    • Extract the last digit by using the modulus operator
    • Increase the extracted digit by the number of digits in total
    • Add the result to the accumulated sum
    • Divide the number by 10 to get rid of the last digit
  6. Compare the accumulated sum with the original number
  7. If both values match, the number is an Armstrong number; otherwise, it is not

How to Check if a Number is an Armstrong Number in Python

An Armstrong number in Python is defined as a number that is equal to the sum of its digits, with each digit raised to the power of the total count of digits in the number. For instance, 370 is an Armstrong number because:

3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370

This section explores multiple approaches to check if a number is an Armstrong number using Python.

Approach 1: Using a For Loop to Check for an Armstrong Number

A for loop is a control flow statement that iterates over a sequence (such as a string, list, tuple, or range) and executes the block of code within it for each item in the sequence. In this scenario, we utilize a for loop to go through each digit of the number, transform it into an integer, elevate it to the power corresponding to the total count of digits, and then accumulate the outcomes.

Code

# Function to check if a number is an Armstrong number using a for loop
def is_armstrong(num):
    n = len(str(num))  # Number of digits
    sum_of_powers = 0  # Initialize sum

    # Iterate through each digit and calculate power
    for digit in str(num):
        sum_of_powers += int(digit) ** n

    return num == sum_of_powers

# User input
num = int(input("Enter a number: "))

if is_armstrong(num):
    print(f"{num} is Armstrong number.")
else:
    print(f"{num} is not Armstrong number.")

Explanation

The function is_armstrong(num) checks if a number is an Armstrong number by first determining the number of digits (n) in the number. It initializes sum_of_powers to 0 and iterates through each digit, raising it to the power of n and adding it to sum_of_powers. Lastly, it compares the sum to the original number, returning True if they match, and False otherwise. If True, it prints that the number is an Armstrong number; if False, it states that it is not. This method efficiently uses a for loop to handle the digits.

Output

Enter a number: 153
153 is Armstrong number.

Approach 2: Using a While Loop to Check for an Armstrong Number

As long as a given condition is true, a while loop is a control flow statement that repeatedly runs a block of code. In this Armstrong code in Python, we use a while loop to extract digits from the given number one by one, raise them to the power of the total number of digits, sum up the results, and then compare the sum with the original number.

Code

# Function to check if a number is an Armstrong number using a while loop
def is_armstrong(num):
    n = len(str(num))  # Number of digits
    sum_of_powers = 0  # Initialize sum
    temp = num  # Store original number

    while temp > 0:
        digit = temp % 10  # Extract last digit
        sum_of_powers += digit ** n  # Add digit^n to sum
        temp //= 10  # Remove last digit

    return num == sum_of_powers

# User input
num = int(input("Enter a number: "))

if is_armstrong(num):
    print(f"{num} is Armstrong number.")
else:
    print(f"{num} is not Armstrong number.")

Explanation

In the provided Armstrong code written in Python, the function is_armstrong(num) starts by setting sum_of_powers = 0 to accumulate the total of each digit elevated to the power of n. The variable temp = num is utilized to retrieve digits while keeping the original number unchanged. The while loop runs as long as temp > 0, continuing until all digits are extracted. Inside the loop, the last digit is obtained using temp % 10, raised to the power of n, and added to sum_of_powers.

The function updates temp using temp //= 10 to remove the last digit, processing all digits. After the loop, it checks if the calculated sum equals the original number, returning True if they match, or False otherwise.

Output

Enter a number: 9474
9474 is Armstrong number.

Approach 3: Using Recursion to Check for an Armstrong Number

A programming method known as recursion involves a function calling itself to resolve smaller versions of an issue. Here, we apply recursion to divide the number into its component digits, raise each digit to the power of the entire number of digits, and then add up the results. The recursion continues until the base case is met, which is when the number becomes zero.

Code

# Function to calculate the Armstrong sum using recursion
def armstrong_recursive(num, n, total=0):
    if num == 0:  # Base case: when all digits are processed
        return total
    return armstrong_recursive(num // 10, n, total + (num % 10) ** n)

# Main function to check if a number is an Armstrong number
def is_armstrong(num):
    return num == armstrong_recursive(num, len(str(num)))

# User input
num = int(input("Enter a number: "))

if is_armstrong(num):
    print(f"{num} is Armstrong number.")
else:
    print(f"{num} is not Armstrong number.")

Explanation

The recursive function armstrong_recursive(num, n, total) breaks down a number digit by digit, summing each digit raised to the power of n. It calls itself with a reduced num until reaching 0, at which point it returns the accumulated total. In the main function is_armstrong(num), the number is passed to armstrong_recursive() with n representing its digit count. The final sum is compared to the original number to determine if it's an Armstrong number.

Output

Enter a number: 9474
9474 is Armstrong number.

Approach 4: Using List Comprehension to Check for an Armstrong Number

List comprehension in Python offers a concise method for generating lists. It enables data transformation and filtering within one clear line of code. In this case, we use list comprehension to iterate over the digits of the Armstrong number Python, raise them to the power of the total number of digits, compute the sum, and compare it with the original number.

Code

# Function to check if a number is an Armstrong number using list comprehension
def is_armstrong(num):
    return num == sum([int(digit) ** len(str(num)) for digit in str(num)])

# User input
num = int(input("Enter a number: "))

print(f"{num} is an Armstrong number." if is_armstrong(num) else f"{num} is not Armstrong number.")

Explanation

In this implementation, the function is_armstrong(num) calculates the sum of the digits, each raised to the power of the total number of digits, using list comprehension. The key part of the function is:

sum([int(digit) ** len(str(num)) for digit in str(num)])

Output

Enter a number: 9474
9474 is Armstrong number.

Approach 5: Using the map() Function to Check for an Armstrong Number

The map() function in Python takes a specified function and applies it to every element in an iterable (such as a list or a string). It transforms each element based on the provided function and returns a map object, which can be converted into other data types (like a list or summed up). In this case, we use map() to apply exponentiation to each digit of the number, then sum up the results to check whether the number is an Armstrong number.

Code

# Function to check if a number is an Armstrong number using map()
def is_armstrong(num):
    n = len(str(num))  # Get the number of digits
    return num == sum(map(lambda x: int(x) ** n, str(num)))  # Apply exponentiation and sum the results

# User input
num = int(input("Enter a number: "))

print(f"{num} is an Armstrong number." if is_armstrong(num) else f"{num} is not Armstrong number.")

Explanation

The map() function is used in this approach to efficiently apply exponentiation to each digit of the number. First, the number is converted to a string so that each digit can be processed individually. The lambda function inside map() converts each character back to an integer, raises it to the power of the total number of digits (n), and applies this transformation to all digits.

The sum() function then adds up these transformed values, and the result is compared with the original number to determine if it is an Armstrong number.

Output

Enter a number: 123
123 is not Armstrong number.

Approach 6: Using the NumPy Function to Check for an Armstrong Number

NumPy, a powerful library for numerical computing in Python, offers vectorized operations that can significantly enhance performance, especially when dealing with large datasets. By leveraging NumPy's capabilities, we can efficiently check for Armstrong numbers across a range of values.

Code

import numpy as np

def is_armstrong(num):
    num_str = str(num)
    num_digits = len(num_str)
    digits = np.array([int(digit) for digit in num_str])
    sum_of_powers = np.sum(np.power(digits, num_digits))
    return sum_of_powers == num

# Example usage
num = int(input("Enter a number: "))
if is_armstrong(num):
    print(f"{num} is Armstrong number.")
else:
    print(f"{num} is not Armstrong number.")

Explanation

This Python program uses the NumPy library to efficiently check whether a number is an Armstrong number. It starts by converting the input number into a string so that each digit can be accessed individually. Then, it counts the total number of digits and creates a NumPy array containing all those digits. Using NumPy's power function, it raises each digit to the power of the number of digits and sums these values. If the sum equals the original number, the program concludes that the number is an Armstrong number. Finally, it prompts the user to enter a number and prints out the result based on this check.

Output

Enter a number: 370
370 is Armstrong number.

Approach 7: Using Memoization to Check for an Armstrong Number

Memoization is a technique to optimize recursive functions by storing previously computed results, thereby avoiding redundant calculations. This is particularly useful when dealing with recursive algorithms that might encounter overlapping subproblems.

Code

def is_armstrong(num):
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = 0
    power_cache = {}

    for digit in num_str:
        digit_int = int(digit)
        if digit_int not in power_cache:
            power_cache[digit_int] = digit_int ** num_digits
        sum_of_powers += power_cache[digit_int]

    return sum_of_powers == num

# Example usage
num = int(input("Enter a number: "))
if is_armstrong(num):
    print(f"{num} is Armstrong number.")
else:
    print(f"{num} is not Armstrong number.")

Explanation

This Python code checks if a number is an Armstrong number using memoization to avoid repeating calculations. It converts the number to a string to access each digit, counts the total digits, and uses a dictionary (power_cache) to store digit powers. For each digit, it either uses the stored power or calculates and saves it. The powered digits are summed and compared to the original number. If they match, it prints that the number is an Armstrong number; otherwise, it says it's not.

Output

Enter a number: 343
343 is not Armstrong number.

Checking Armstrong Number of n Digits

Here is the Armstrong number code in Python using recursion to check if a number with n digits is an Armstrong number. It allows you to check any number, regardless of its digit length.

Code

def power(base, exp):
    # Recursive function to calculate base^exp
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

def sum_of_powers(num, n):
    # Recursively calculate sum of digits raised to power n
    if num == 0:
        return 0
    digit = num % 10
    return power(digit, n) + sum_of_powers(num // 10, n)

def is_armstrong(num):
    n = len(str(num))  # Number of digits
    return num == sum_of_powers(num, n)

# Example usage
number = int(input("Enter a number: "))
if is_armstrong(number):
    print(f"{number} is Armstrong number.")
else:
    print(f"{number} is not Armstrong number.")

Explanation

This code checks if a number is an Armstrong number by using recursion. First, it counts how many digits the number has. Then, it breaks the number down digit by digit, raising each digit to the power of the total number of digits and adding these results together. This is done with a recursive function that keeps calling itself until all digits are processed. Finally, it compares the sum of these powered digits with the original number. If they are the same, the number is an Armstrong number; if not, it isn't.

Output

Enter a number: 371
371 is Armstrong number.

Checking Armstrong Number for 3 Digits

Here's a Python program to check Armstrong number for 3 digits using a while loop.

Code

def is_armstrong_3digits(num):
    original_num = num
    sum_of_cubes = 0

    while num > 0:
        digit = num % 10
        sum_of_cubes += digit ** 3
        num = num // 10

    return sum_of_cubes == original_num

# Example usage
number = int(input("Enter a 3-digit number: "))
if 100 <= number <= 999:
    if is_armstrong_3digits(number):
        print(f"{number} is an Armstrong number.")
    else:
        print(f"{number} is not an Armstrong number.")
else:
    print("Please enter a valid 3-digit number.")

Explanation

This program specifically checks Armstrong numbers with exactly three digits. It uses a while loop to process each digit of the number one by one. Inside the loop, it extracts the last digit using the modulus operator (% 10), raises it to the power of 3, and adds it to a running total. Then, it removes the last digit by dividing the number by 10 (integer division). After processing all digits, the program compares the total sum of cubes with the original number. If they are equal, it confirms the number is an Armstrong number.

Output

Enter a 3-digit number: 407
407 is an Armstrong number.

Checking Armstrong Number for 4 Digits

Here is a Python program that uses the map() method to determine whether a 4-digit number is an Armstrong number.

Code

def is_armstrong_4digit(num):
    # Convert number to string to access each digit
    digits = str(num)
    if len(digits) != 4:
        return False  # Only check for 4-digit numbers

    # Use map to convert each digit back to int and raise to the power of 4
    powered_digits = map(lambda x: int(x) ** 4, digits)
    total = sum(powered_digits)

    return total == num

# Example usage
number = int(input("Enter a 4-digit number: "))
if is_armstrong_4digit(number):
    print(f"{number} is a 4-digit Armstrong number.")
else:
    print(f"{number} is not a 4-digit Armstrong number.")

Explanation

This code focuses specifically on 4-digit numbers. It first checks if the input has exactly 4 digits. Then, it uses the map() function combined with a lambda to raise each digit to the power of 4. These powered digits are summed, and the total is compared to the original number. If they match, the number is a 4-digit Armstrong number; otherwise, it's not.

Output

Enter a 4-digit number: 1634
1634 is a 4-digit Armstrong number.

Checking Armstrong Numbers in a Given Range or Interval

A number that equals the sum of its individual digits, each raised to the power of the total number of digits, is known as an Armstrong number (or narcissistic number). This technique uses list comprehension to locate every Armstrong number within a certain range.

Code

# Function to find all Armstrong numbers in a given range
def find_armstrong_numbers(start, end):
    return [num for num in range(start, end + 1) if num == sum(int(digit) ** len(str(num)) for digit in str(num))]

# User input for range
start, end = map(int, input("Enter range (start end): ").split())

# Finding and displaying Armstrong numbers
armstrong_nums = find_armstrong_numbers(start, end)
print(f"Armstrong numbers in range {start}-{end}: {armstrong_nums}")

Explanation

This Python program finds Armstrong numbers in a given range using list comprehension. The function find_armstrong_numbers(start, end) checks each number by summing its digits, each raised to the power of the total digits. If the sum matches the number, it is added to the list.

The user inputs a range, which is converted to integers. The function is then called, and the Armstrong numbers are printed. This method is efficient for small to moderate ranges but may need optimization for larger numbers.

Output

Enter range (start end): 1000 10000
Armstrong numbers in range 1000-10000: [1634, 8208, 9474]

Checking Armstrong Numbers in Different Number Systems

While this concept is commonly applied in the decimal system (base-10), it can be extended to other number systems like binary (base-2), octal (base-8), and hexadecimal (base-16).

Armstrong Numbers in Binary (Base-2)

When checking for an Armstrong number in binary, the process involves converting the given number into its base-2 equivalent.

Process:

Example: For the number 5:

Armstrong Numbers in Octal (Base-8)

To determine if a number is an Armstrong number in the octal system:

Process:

Example: For the number 64:

Armstrong Numbers in Hexadecimal (Base-16)

For hexadecimal Armstrong numbers, the approach adapts to base-16:

Process:

Example: For the number 370:

Armstrong Number Program in Python: Common Errors and Best Practices

Here are common errors to avoid when writing an Armstrong number program in Python, along with best practices to follow for accurate and efficient code.

Common Errors in Armstrong Number Programs

Error Type Description Fix
Incorrect Use of Division Operators Using / (floating-point division) instead of // (integer division) can lead to unexpected results when extracting digits Always use // for integer division when breaking down numbers
Hardcoding the Number of Digits Assuming a fixed number of digits (e.g., 3) limits the program's applicability Determine the number of digits dynamically using len(str(num))
Modifying the Original Number Altering the input number during processing can lead to incorrect comparisons at the end Store the original number in a separate variable before processing
Incorrect Exponentiation Misusing the exponentiation operator (e.g., using ^ instead of **) results in incorrect calculations Use ** for exponentiation in Python
Not Handling Negative Numbers or Non-Integer Inputs Failing to validate input can cause runtime errors or incorrect results Implement input validation to ensure the number is a non-negative integer

Best Practices for Writing Armstrong Number Programs

Best Practice Description
Use Meaningful Variable Names Choose descriptive names like original_number, sum_of_powers, and num_digits to enhance code readability
Implement Input Validation Ensure the program handles invalid inputs gracefully by checking if the input is a non-negative integer
Modularize the Code Encapsulate the logic in a function, such as is_armstrong(number), to promote reusability and clarity
Optimize Digit Extraction Use efficient methods like converting the number to a string or using arithmetic operations to extract digits
Include Comments and Documentation Include comments that clarify the function of code blocks, which facilitates comprehension and maintenance

Real-World Uses of Armstrong Numbers

Armstrong numbers seem like a mathematical novelty, but they are useful in programming. They help developers strengthen their understanding of essential concepts.

Educational and Practical Applications

Application Area Description
Learning Programming Basics Armstrong numbers are great for beginners to learn programming. They help you practice using loops, conditions, and number operations, such as breaking a number into digits
Improving Problem-Solving Skills Writing a program to check for an Armstrong number is like solving a mini puzzle. It helps you think logically and improves your ability to solve problems with code
Exploring Interesting Number Patterns Armstrong numbers have a unique pattern: each digit raised to a power and added gives the original number. This makes them interesting for learning about number theory
Teaching How Algorithms Work Teachers often use Armstrong numbers to explain algorithms. They're a simple way to show how to loop through digits and perform calculations step by step
Fun for Math Lovers People who enjoy math puzzles like exploring Armstrong numbers. Finding new ones or spotting patterns is a fun way to stay engaged with math
Practicing Data Validation Concepts Although not used in real apps, Armstrong numbers are a good example for learning how to write code that checks if input meets certain rules, like in data validation
Understanding Basics of Cryptography The logic behind Armstrong numbers—breaking numbers into digits, using powers—is similar to the math used in encryption. So, they're helpful when learning the basics of cryptography

These concepts are particularly valuable for beginners in Python and those preparing for technical interviews or coding competitions.

Conclusion

The Armstrong number program in Python offers a great opportunity to practice key programming concepts like mathematical logic, loops, recursion, and list comprehensions. By separating a number into its digits, raising each to a specific power, and adding the results, the program determines if the number qualifies as an Armstrong number.

There are various ways to implement this in Python, such as:

Each approach provides an efficient method for checking Armstrong numbers. Although Armstrong numbers may not have major practical uses, they are valuable exercises for enhancing problem-solving abilities, improving code efficiency, and preparing for coding interviews.

Frequently Asked Questions

What is an Armstrong number?

An Armstrong number, also known as a narcissistic number, is a number that equals the sum of its digits, with each digit raised to the power of the total number of digits. For example, 8208 is an Armstrong number because:

8^4 + 2^4 + 0^4 + 8^4 = 4096 + 16 + 0 + 4096 = 8208

How do you check if a number is an Armstrong number in Python?

You can check if a number is an Armstrong number by converting it into its individual digits, raising each digit to the power of the total number of digits, summing the results, and comparing the sum with the original number. This can be done using loops, recursion, or list comprehension.

What are some real-world applications of Armstrong numbers?

While Armstrong numbers don't have direct real-world applications, they are commonly used in programming exercises, algorithm development, and technical interviews to practice concepts like loops, recursion, and mathematical computations.

What is the difference between a for loop and a while loop approach?

A for loop is used to iterate over the digits of a number directly, whereas a while loop extracts digits one by one using the modulus (%) and division (//) operations. The while loop approach is more manual but useful for handling numerical operations without converting the number to a string.

Can we use recursion to check Armstrong numbers?

Yes, recursion can be used by repeatedly extracting digits, raising them to a power, and summing the results until the base case (the number becomes 0) is met. This approach reduces redundancy and makes the function more modular.

How can I find all Armstrong numbers within a range?

To find Armstrong numbers within a given range, iterate through each number in the range and check if it satisfies the Armstrong condition. Python list comprehension is an efficient way to filter out Armstrong numbers within a specified range.

What is the most efficient way to check for Armstrong numbers?

The most efficient approach is using list comprehension or the map() function, as they reduce code complexity and execute in fewer lines. However, for larger numbers, optimized methods using mathematical properties or precomputed results can further improve performance.


Related Articles


Source: NxtWave
Contact: [email protected]
Phone: +919390111761 (WhatsApp only)