Find an Armstrong Number Using Recursion in Python

Recently, while teaching Python to a group of data enthusiasts in New York, one of my students asked me how to find an Armstrong number using recursion in Python.

At that moment, I realized that while many people know how to check an Armstrong number using loops, very few understand how to do it recursively, which is actually a cleaner and more Pythonic approach.

So, in this tutorial, I’ll walk you through everything you need to know about Armstrong numbers and how to check them using recursion in Python.

Armstrong Number in Python

An Armstrong number (also known as a Narcissistic number) is a number that is equal to the sum of its 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)
  • 9474 is also an Armstrong number because:
    (9^4 + 4^4 + 7^4 + 4^4 = 9474)

In simple terms, if you take each digit, raise it to the power of the total number of digits, and add them up, you get the original number itself.

Why Use Recursion in Python?

In Python, recursion is when a function calls itself to solve smaller parts of a larger problem. Using recursion for an Armstrong number makes the code elegant and easy to read. Instead of using loops, recursion helps us break the problem into smaller steps, one digit at a time.

This approach is especially useful when you want to strengthen your understanding of recursive logic in Python.

Steps to Check Armstrong Number Using Recursion in Python

Before jumping into the code, let’s break down the logic step by step:

  1. Take a number as input.
  2. Find the number of digits in the number.
  3. Write a recursive function that extracts each digit, raises it to the power of the total digits, and adds them up.
  4. Compare the result with the original number.
  5. If both are equal, it’s an Armstrong number.

Method 1 – Use Recursion in Python

Let’s start with the simplest approach using recursion.

Here’s the complete Python code:

# Python program to check Armstrong number using recursion

def power_sum(num, power):
    """Recursive function to calculate the sum of digits raised to the given power."""
    if num == 0:
        return 0
    else:
        return (num % 10) ** power + power_sum(num // 10, power)

def is_armstrong(num):
    """Function to check if a number is Armstrong using recursion."""
    digits = len(str(num))
    result = power_sum(num, digits)
    return result == num

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

I executed the above example code and added the screenshot below.

armstrong number

The power_sum() function recursively breaks down the number, raising each digit to the given power and summing the results.

Suppose we input 153.

  • The number of digits = 3
  • The recursive function works as:
    (3^3 + 5^3 + 1^3 = 153)

Each recursive call handles one digit and adds it to the total sum. When the number becomes zero, recursion stops.

Method 2 – Use Recursion with a Helper Function in Python

Sometimes, it’s cleaner to use a helper function to manage the recursion separately.

Here’s an alternate version of the Python code:

# Python program to check Armstrong number using recursion with helper function

def armstrong_helper(num, power):
    if num == 0:
        return 0
    return (num % 10) ** power + armstrong_helper(num // 10, power)

def check_armstrong(num):
    power = len(str(num))
    sum_of_powers = armstrong_helper(num, power)
    return sum_of_powers == num

# Example usage
for test_num in [153, 370, 9474, 9475]:
    if check_armstrong(test_num):
        print(f"{test_num} is an Armstrong number.")
    else:
        print(f"{test_num} is not an Armstrong number.")

I executed the above example code and added the screenshot below.

what is armstrong number

This version separates the logic into two functions, one for recursion and one for validation. It’s a great way to write clean, reusable Python code that’s easy to maintain.

Method 3 – Armstrong Number Using Recursion and String Conversion

Another interesting way to solve this problem is by using string manipulation in Python. In this method, we convert the number into a string and recursively process one character at a time.

Here’s how it looks:

# Python program to check Armstrong number using recursion and string conversion

def armstrong_str(num_str, power):
    if not num_str:
        return 0
    return int(num_str[0]) ** power + armstrong_str(num_str[1:], power)

def is_armstrong_str(num):
    num_str = str(num)
    power = len(num_str)
    return armstrong_str(num_str, power) == num

# Example usage
num = 9474
if is_armstrong_str(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

I executed the above example code and added the screenshot below.

armstrong in python

This approach is simple and readable, ideal for beginners learning recursion in Python. It also demonstrates how Python’s string slicing can be effectively combined with recursion.

Bonus: Find All Armstrong Numbers in a Range Using Recursion

Let’s take it a step further. What if you want to find all Armstrong numbers within a given range, say, from 100 to 10,000?

Here’s how you can do that using recursion:

# Python program to find all Armstrong numbers in a range using recursion

def power_sum(num, power):
    if num == 0:
        return 0
    return (num % 10) ** power + power_sum(num // 10, power)

def is_armstrong(num):
    power = len(str(num))
    return num == power_sum(num, power)

def find_armstrong_recursive(start, end):
    if start > end:
        return []
    if is_armstrong(start):
        return [start] + find_armstrong_recursive(start + 1, end)
    else:
        return find_armstrong_recursive(start + 1, end)

# Example usage
armstrong_numbers = find_armstrong_recursive(100, 10000)
print("Armstrong numbers between 100 and 10000 are:")
print(armstrong_numbers)

This function uses recursion to iterate through a range and collect all Armstrong numbers. It’s an efficient and elegant way to explore recursion beyond simple checks.

Common Mistakes to Avoid

When writing recursive functions in Python, keep these tips in mind:

  • Always define a base case. Without it, recursion will continue infinitely.
  • Avoid very large numbers. Deep recursion can hit Python’s recursion limit.
  • Use helper functions. They make your code modular and easier to debug.

These small details make your Python code more reliable and professional.

Real-Life Use Case Example

While Armstrong numbers are mostly used for learning recursion and number theory, they can also be applied in digital security and cryptography, where mathematical patterns play a role in encryption algorithms.

For instance, when I worked on a Python-based educational app for middle school students in Texas, I incorporated Armstrong numbers into a gamified math quiz, and it was a hit!

Conclusion

So, that’s how you can find an Armstrong number using recursion in Python. We explored multiple methods, from simple recursive checks to range-based searches, and discussed how recursion can make your Python code more elegant and powerful.

If you’re new to recursion, I recommend experimenting with small numbers first and gradually building your confidence.

Once you master this concept, you’ll find recursion incredibly useful in solving many other Python problems, from factorials to Fibonacci sequences and beyond.

You may also like to read other articles on Python:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.