Armstrong Number In Python

Ayushi Trivedi Last Updated : 07 Jun, 2024
8 min read

Introduction

Welcome to our comprehensive guide on Armstrong numbers! Here, we explore the intriguing concept of Armstrong numbers. We begin by defining Armstrong numbers and their unique properties through examples. You will learn how to check if a number is an Armstrong number using Python. We will also discover various methods like iterative, recursive, and mathematical approaches. Additionally, we delve into advanced techniques such as using list comprehension, functional programming, and more. This article serves as a valuable resource for understanding Armstrong numbers and their applications in programming and beyond.

Armstrong number

Learning Outcomes

  • Understand the definition and characteristics of Armstrong numbers.
  • Find out how to use Python to determine if a given number is an Armstrong number.
  • Explore various methods and approaches to calculate Armstrong numbers.
  • Gain familiarity with programming concepts such as loops, conditionals, functions and recursion through Armstrong number exercises.
  • Recognize how Armstrong numbers can be used to improve problem-solving and programming skills.

What is an Armstrong Number?

Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. It is also known as a narcissistic number or pluperfect number.

For example:

  • 153 is an Armstrong number because 13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153
  • 9474 is an Armstrong number because 94+44+74+44=94749^4 + 4^4 + 7^4 + 4^4 = 947494+44+74+44=9474

General Formula:

abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ….

Steps to Check Armstrong Number in Python

Let us now look into the basic steps on how we can check whether a number is Armstrong or not.

  • Step1: Input the number.
  • Step2: Calculate the number of digits.
  • Step3: Compute the sum of powers.
  • Step4: Check if the sum equals the original number.

Python Program to Check Armstrong Number

Let’s create a program that checks if a given number is an Armstrong number using Python.

# Python program to determine whether
# a number is an Armstrong number or not

# Function to compute the power of a digit
def compute_power(base, exponent):
    if exponent == 0:
        return 1
    half_power = compute_power(base, exponent // 2)
    if exponent % 2 == 0:
        return half_power * half_power
    else:
        return base * half_power * half_power

# Function to determine the number of digits in the number
def digit_count(number):
    count = 0
    while number > 0:
        count += 1
        number //= 10
    return count

# Function to check if the number is an Armstrong number
def is_armstrong_number(number):
    num_digits = digit_count(number)
    temp = number
    armstrong_sum = 0
    
    while temp > 0:
        digit = temp % 10
        armstrong_sum += compute_power(digit, num_digits)
        temp //= 10
    
    return armstrong_sum == number

# Driver code to test the function
test_numbers = [153, 1253]
for num in test_numbers:
    print(f"{num} is an Armstrong number: {is_armstrong_number(num)}")

Output:

153 is an Armstrong number: True
1253 is an Armstrong number: False

Time Complexity: O(n)

  • Here, n is the number of digits in the number.
  • The time complexity is O(n) because we iterate through each digit of the number.

Auxiliary Space: O(1)

  • The space complexity is O(1) as we use a constant amount of space.

Methods to Calculate Armstrong Number

We have multiple methods using which we can find Armstrong number. Let us look into those methods one by one in detail with code and their output.

Using Iterative Method

By iteratively increasing each digit of the number to the power of all the digits and adding the results, the approach works through the entire number of digits. Beginning users can benefit from this strategy because it is simple to use and comprehend. It employs fundamental control structures like as conditionals and loops. This method is different from others due to its simplicity and direct approach without requiring additional functions or advanced concepts.

def is_armstrong_number(num):
    digits = [int(d) for d in str(num)]
    num_digits = len(digits)
    sum_of_powers = sum(d ** num_digits for d in digits)
    return num == sum_of_powers

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using Recursive Method

The recursive method uses a recursive function to calculate the sum of the digits raised to the power of the number of digits. It breaks down the problem into smaller instances, calling itself with a reduced number until a base case is met. This method is elegant and useful for learning recursion, which is a fundamental concept in computer science. It differs from the iterative method by avoiding explicit loops and instead relying on function calls.

def sum_of_powers(num, num_digits):
    if num == 0:
        return 0
    else:
        return (num % 10) ** num_digits + sum_of_powers(num // 10, num_digits)

def is_armstrong_number(num):
    num_digits = len(str(num))
    return num == sum_of_powers(num, num_digits)

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using Mathematical Approach

This method uses mathematical operations to isolate each digit, compute the required power, and sum the results. By employing arithmetic operations like division and modulus, it processes each digit in a straightforward manner. This approach emphasizes the mathematical foundation of the problem, differing from others by focusing on the number’s arithmetic properties rather than looping or recursion.

def is_armstrong_number(num):
    num_digits = len(str(num))
    temp = num
    sum_of_powers = 0
    
    while temp > 0:
        digit = temp % 10
        sum_of_powers += digit ** num_digits
        temp //= 10
    
    return num == sum_of_powers

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using List Comprehension

This technique creates a list of numerals raised to the necessary power using Python’s list comprehension, then sums the list. This method is succinct and leverages the expressive syntax of Python to create lists. It is different from traditional loop-based methods because it compresses the logic into a single, readable line of code, making it more Pythonic and often more readable.

def is_armstrong_number(num):
    num_digits = len(str(num))
    return num == sum([int(digit) ** num_digits for digit in str(num)])

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using Functional Programming

To handle the numbers, this approach uses higher-order functions like map and reduce. Every digit in the list is given a function by map, which then aggregates the results into a single value. It displays paradigms for functional programming, which are distinct from imperative programming styles found in other techniques. This method may result in code that is more condensed and possibly more effective.

from functools import reduce

def is_armstrong_number(num):
    num_digits = len(str(num))
    return num == reduce(lambda acc, digit: acc + int(digit) ** num_digits, str(num), 0)

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using a Generator Function

A generator function is used to yield Armstrong numbers up to a specified limit, generating numbers on-the-fly without storing them in memory. This method is memory efficient and suitable for generating large sequences of numbers. It differs from others by leveraging Python’s generator capabilities, which can handle large data sets more efficiently than storing them in lists.

def armstrong_numbers(limit):
    for num in range(limit + 1):
        num_digits = len(str(num))
        if num == sum(int(digit) ** num_digits for digit in str(num)):
            yield num

# Generate Armstrong numbers up to 10000
for number in armstrong_numbers(10000):
    print(number)

Using String Manipulation

The number is treated as a string in this technique, and the results are summed after each character is iterated over to convert it back to an integer and raise it to the power of the number of digits. Unlike arithmetic-based approaches, it is straightforward and makes use of the string representation of numbers using string operations.

def is_armstrong_number(num):
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)
    return num == sum_of_powers

# Check a number
print(is_armstrong_number(153))  # Output: True
print(is_armstrong_number(123))  # Output: False

Using a Lookup Table for Powers

Precomputing the powers of digits and storing them in a lookup table speeds up the calculation process. This method is efficient for large ranges of numbers, as it avoids redundant power calculations. It differs from others by introducing a preprocessing step to optimize the main computation.

def precompute_powers(max_digits):
    powers = {}
    for digit in range(10):
        powers[digit] = [digit ** i for i in range(max_digits + 1)]
    return powers

def is_armstrong_number(num, powers):
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = sum(powers[int(digit)][num_digits] for digit in num_str)
    return num == sum_of_powers

# Precompute powers up to a reasonable limit (e.g., 10 digits)
powers = precompute_powers(10)

# Check a number
print(is_armstrong_number(153, powers))  # Output: True
print(is_armstrong_number(123, powers))  # Output: False

Using NumPy for Vectorized Computation

NumPy, a powerful numerical library, is used for vectorized operations on arrays of digits. This method is highly efficient for handling large datasets due to NumPy’s optimized performance. It stands out by leveraging the power of NumPy to perform operations in a vectorized manner, reducing the need for explicit loops.

import numpy as np

def find_armstrong_numbers(limit):
    armstrong_numbers = []
    for num in range(limit + 1):
        digits = np.array([int(digit) for digit in str(num)])
        num_digits = digits.size
        if num == np.sum(digits ** num_digits):
            armstrong_numbers.append(num)
    return armstrong_numbers

# Find Armstrong numbers up to 10000
print(find_armstrong_numbers(10000))

Using Memoization

Memoization stores previously computed sums of powers to avoid redundant calculations, speeding up the checking process. This method is beneficial for repeated checks of similar numbers. It is different from others by incorporating a caching mechanism to optimize performance, especially useful in scenarios with many repeated calculations.

def is_armstrong_number(num, memo):
    if num in memo:
        return memo[num]
    
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)
    memo[num] = (num == sum_of_powers)
    return memo[num]

# Initialize memoization dictionary
memo = {}

# Check a number
print(is_armstrong_number(153, memo))  # Output: True
print(is_armstrong_number(123, memo))  # Output: False

Applications of Armstrong Numbers

Armstrong numbers have several applications in various fields. Here are some of the notable applications:

  • Number Theory and Mathematics: Armstrong numbers are used in number theory to study properties of numbers. They serve as an interesting example of self-referential numbers in mathematical discussions.
  • Programming and Algorithm Design: Armstrong numbers are commonly used as exercises in programming courses to practice loops, conditionals, functions, and mathematical operations. They provide a practical way to demonstrate and understand recursion and iterative approaches in programming.
  • Error Detection in Telecommunications: In telecommunication systems, Armstrong numbers can be used as a simple error-checking mechanism. By verifying whether a number sent is equal to the sum of its digits raised to a power, errors in transmission can be detected.
  • Cryptographic Applications: In some cryptographic algorithms, Armstrong numbers can be used as part of the validation process. They may be used to generate keys or perform checks to ensure data integrity.
  • Educational Purposes: Armstrong numbers are frequently employed in classroom instruction to educate pupils to mathematics and programming principles. They can serve as examples of the significance of effective algorithms and the effects of various programming methods.

Conclusion

This article explores Armstrong numbers, their definitions, properties, and Python methods for identifying them. It covers iterative, recursive, mathematical, and computational approaches. Armstrong numbers are useful for learning mathematical concepts and improving programming abilities. They have applications in error detection, cryptography, and education. This knowledge equips individuals to tackle challenges and explore the world of numbers in programming and mathematics.

Don’t miss this chance to improve your skills and advance your career. Learn Python with us! This course is suitable for all levels.

Frequently Asked Questions

Q1. What is an Armstrong number?

A. An Armstrong number, also known as a narcissistic or pluperfect number, is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number.

Q2. Why are Armstrong numbers also called narcissistic numbers?

A. Armstrong numbers are sometimes referred to as narcissistic numbers because they maintain a property of self-reference or self-regard. This is because the number itself is equal to the sum of its own digits raised to the power of the number of digits.

Q3. What is the significance of Armstrong numbers in programming?

A. Armstrong numbers are commonly used as examples in programming exercises to demonstrate various programming techniques such as loops, conditionals, functions, recursion, and mathematical computations. They provide a practical way to test and improve programming skills.

Q4. Can Armstrong numbers be negative or zero?

A. No, by definition, Armstrong numbers are positive integers. Negative numbers and zero cannot be Armstrong numbers because the sum of the digits raised to the power of the number of digits will not equal a negative number or zero.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details