Back

Armstrong Number Program in Python: Easy Code with Explanation

27 May 2025
6 min read

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. In this blog, we will explore how to write an Armstrong number program in Python that checks whether a given number is an Armstrong number. This program is not only a fun challenge but also helps sharpen problem-solving skills and deepen your grasp of Python programming.

What is an Armstrong number?

It is also called a Narcissistic number or Pluperfect Digital Invariant (PPDI), 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 also the Armstrong number program in Python, and are used to practice loops, recursion, and mathematical operations.

Formula:

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

d1n+d2n+⋯+dm= original number

where:

  • d1​,d2​,..., dm are the digits of the number.
  • n is the number of digits.

Example of an Armstrong Number

Take 153 as an example:

  • It has three digits: 1, 5, and 3.
  • Each digit is raised to the power of 3 (since there are three digits): 1^3+5^3+3^3=1+125+27=153
  • The number 153 is considered an Armstrong number because the sum of its digits raised to the power of three equals the original number.

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:
  6. Extract the last digit by using the modulus operator.
  7. Increase the extracted digit by the number of digits in total.
  8. Add the result to the accumulated sum.
  9. Divide the number by 10 to get rid of the last digit.
  10. Compare the accumulated sum with the original number.
  11. 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. 370, for instance, is an Armstrong number due to:

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

We'll explore a simple way 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. Here’s the Armstrong Number Program in Python using a for loop:

Code

Below is a code implementation of an Armstrong number in Python using for loop:

# 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. Here’s the Armstrong number program in Python using while loop:

Code

The Python code below uses a while loop to implement an Armstrong number:

# 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. Here’s the Armstrong Number Program in Python using recursion:

Code

Here is an example of Python code that uses recursion to implement an Armstrong number:

# 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. Here’s the Armstrong number program in Python using List comprehension:

Code

This is an example of Python code that implements an Armstrong number using list comprehension:

# 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.")

Output:

Enter a number: 9474
9474 is 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)])

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. Here’s the Armstrong number Python program using the map() function:

Code

This Python code demonstrates how to implement an Armstrong number using map():

# 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.")

Output

Enter a number: 123
123 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.

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

An example of Python code that implements an Armstrong number using a NumPy function is provided here:

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

Here is a version of Python code that implements an Armstrong number using Memoization:

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:

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, along with a clear explanation:

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, along with a clear explanation:

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 else narcissistic number). This technique uses list comprehension to locate every Armstrong number within a certain range. Here’s the Armstrong code in Python to check Armstrong numbers in a given 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 of the code

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.

  • First, the number is converted to binary.
  • Next, each individual binary digit (which will only be '0' or '1') is identified.
  • The total count of digits in its binary representation is determined.
  • Finally, the sum is calculated where each binary digit is raised to the power of the total digit count. If this sum precisely matches the original number, then it qualifies as a binary Armstrong number.

Example:

For the number 5:

  • Binary representation: 101
  • Number of digits: 3
  • Calculation: 1³ + 0³ + 1³ = 1 + 0 + 1 = 2
    Since 2 ≠ 5, 5 is not an Armstrong number in binary.

Armstrong Numbers in Octal (Base-8)

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

  • The number is first transformed into its octal form.
  • Then, each octal digit (ranging from 0 to 7) is extracted.
  • The total number of digits in the octal representation is counted.
  • The computation involves summing each octal digit raised to the power of the total number of octal digits. A match between this sum and the original number confirms it as an octal Armstrong number.

Example:

For the number 64:

  • Octal representation: 100
  • Number of digits: 3
  • The calculation is: 1³ + 0³ + 0³ = 1 + 0 + 0 = 1.
    Since 1 ≠ 64, 64 is not an Armstrong number in octal.

Armstrong Numbers in Hexadecimal (Base-16)

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

  • The initial step is to convert the number to its hexadecimal equivalent.
  • Subsequently, every hexadecimal digit (0-9 and A-F, where A=10, B=11, etc.) is isolated.
  • The total count of digits within the hexadecimal representation is ascertained.
  • The final calculation involves summing each hexadecimal digit raised to the power of the total hexadecimal digits. If this computed sum aligns with the original number, it is recognized as a hexadecimal Armstrong number.

Example:

For the number 370:

  • Hexadecimal representation: 0x172
  • Number of digits: 3
  • Calculation: 1³ + 7³ + 2³ = 1 + 343 + 8 = 352
    Since 352 ≠ 370, 370 is not an Armstrong number in hexadecimal.

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

1. Incorrect Use of Division Operators
Using / (floating-point division) instead of // (integer division) can lead to unexpected results when extracting digits.
Fix: Always use // for integer division when breaking down numbers.

2. Hardcoding the Number of Digits
Assuming a fixed number of digits (e.g., 3) limits the program's applicability.
Fix: Determine the number of digits dynamically using len(str(num)).

3. Modifying the Original Number
Altering the input number during processing can lead to incorrect comparisons at the end.
Fix: Store the original number in a separate variable before processing.

4. Incorrect Exponentiation
Misusing the exponentiation operator (e.g., using ^ instead of **) results in incorrect calculations.
Fix: Use ** for exponentiation in Python.

5. Not Handling Negative Numbers or Non-Integer Inputs
Failing to validate input can cause runtime errors or incorrect results.
Fix: Implement input validation to ensure the number is a non-negative integer.

Best Practices for Writing Armstrong Number Programs

1. Use Meaningful Variable Names
Choose descriptive names like original_number, sum_of_powers, and num_digits to enhance code readability.

2. Implement Input Validation
Ensure the program handles invalid inputs gracefully by checking if the input is a non-negative integer.

3. Modularize the Code
Encapsulate the logic in a function, such as is_armstrong(number), to promote reusability and clarity.

4. Optimize Digit Extraction
Use efficient methods like converting the number to a string or using arithmetic operations to extract digits.

5. 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, such as:

1. 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.

2. 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.

3. 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.

4. 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.

5. 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.

6. 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.

7. Understanding Basics of Cryptography

The logic behind Armstrong numbers is breaking numbers into digits, using powers, which 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 using for loops, while loops, recursion, list comprehensions, or the map() function, each providing an efficient approach. 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

1. 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

2. 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.

3. 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.

4. 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.

5. 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.

6. 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.

7. 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.

Read More Articles

Chat with us
Chat with us
Talk to career expert