Calculation of Armstrong Number in Python

Calculation of Armstrong Number in Python

27 May 2025
Beginner
5.4K Views
32 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

An Armstrong number in Python is a special type of number in mathematics. It is a number that is equal to the sum of its own digits, where each digit is raised to the power of the total number of digits in the number. It is also known as a Narcissistic number.

An Armstrong number in Python programs helps beginners practice working with loops, conditionals, and number manipulation in PythonThey also improve problem-solving skills by teaching how to break down a number and apply logic step by step.

In the Python tutorial, I’ll explain how to identify Armstrong Numbers in Python with proper examples.

What is an Armstrong Number in Python?

An Armstrong number in Python is a number that is equal to the sum of its digits, with each digit raised to the power of the total number of digits in the number. This means the number itself matches the special calculation done using its digits.

Armstrong Number in Python

Which can't be Armstrong Numbers?

There are some cases where numbers can never be an Armstrong number. Let's break it down together.

  • Negative numbers cannot be Armstrong numbers because the definition only applies to positive integers.
  • Numbers with leading zeros (like 0123) are not considered because leading zeros do not change a number's value.
  • Most large random numbers are not Armstrong numbers because it is very rare for a number to exactly equal the sum of its digits raised to the power of the number of digits.
  • Numbers where the sum of the digits raised to the power does not match the original number cannot be Armstrong numbers.

Mathematical Representation of Armstrong Number

An Armstrong Number of n digits is when the sum of its digits, each raised to the power of the total number of digits, equals the number itself:

abcd… = a^n+b^n+c^n+d^n......

  • Here, you take each digit (a, b, c, d, …) of the number and raise it to the power of the total number of digits (n).
  • For example, if you have a 3-digit number like 370: 370 = 3^3+7^3+0^3 = 27+343+0 = 0.
  • This shows that 370 is an Armstrong Number.

Let's understand Armstrong Number in Python by a given example:

def is_armstrong(num):
    num_str = str(num)
    num_digits = len(num_str)
    total = 0

    for digit in num_str:
        total += int(digit) ** num_digits

    return total == num

num1 = 407
if is_armstrong(num1):
    print(num1, "is an Armstrong number.")
else:
    print(num1, "is not an Armstrong number.")

num2 = 372
if is_armstrong(num2):
    print(num2, "is an Armstrong number.")
else:
    print(num2, "is not an Armstrong number.")

Output

407 is an Armstrong number.
372 is not an Armstrong number.

Explanation

In the above example:

  • The function is_armstrong(num) takes a number, breaks it into digits, and raises each digit to the power of the total number of digits. It then adds all those powered digits together.
  • It checks if this total equals the original number. If yes, it means the number is an Armstrong number and returns True; otherwise, it returns False.
  • The code tests two numbers, 407 and 372.Based on the function's result, it prints whether each one is an Armstrong number.

Different Approaches to Check Armstrong Number in Python

Let's understand various ways to find the Armstrong function in Python.

1. Digit-by-Digit Sum Approach to Check for an Armstrong Number

import math
def isArmstrong(num):
	n = num
	numDigits = 0
	sum = 0	
	# Find number of digits in num
	while n > 0:
		n //= 10
		numDigits += 1	
	n = num	
	# Calculate sum of digits raised to the power of numDigits
	while n > 0:
		digit = n % 10
		sum += math.pow(digit, numDigits)
		n //= 10	
	# Check if num is Armstrong number or not
	if sum == num:
		return True
	return False
num1 = 407
if isArmstrong(num1):
	print(num1, "is an Armstrong number.")
else:
	print(num1, "is not an Armstrong number.")
num2 = 372
if isArmstrong(num2):
	print(num2, "is an Armstrong number.")
else:
	print(num2, "is not an Armstrong number.")

Output

407 is an Armstrong number.
372 is not an Armstrong number. 

Explanation

In this example;

  • In the above code, first of all, in the isArmstrong() function, we have found the number of digits in the given number and stored it in the numDigits variable.
  • Then, we extracted each digit from the given numbers num1 and num2, raised it to the power of the number of digits, and added it to the sum variable.
  • If the sum is evaluated to the given number, then it is an Armstrong number; otherwise, it is not.

2. Python program to check if a number is an Armstrong number in the return statement

def is_armstrong_number(number):
	return sum(int(digit)**len(str(number)) for digit in str(number)) == number

number = 1634
if is_armstrong_number(number):
	print(f"{number} is an Armstrong number")
else:
	print(f"{number} is not an Armstrong number")

Output

1634 is an Armstrong number

Explanation

In the above example;

  • In the above code, the function is_armstrong_number calculates the sum of each digit raised to the power of the number of digits in the number using a generator expression and the sum() function.
  • It then compares this sum to the original number to determine if it's an Armstrong number.

3. Check Armstrong number of n digits using a while loop

number = 54748
# Changing num variable to string
order = len(str(number))
sum = 0
temp = number
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10
if number == sum:
   print(number,"is an Armstrong number")
else:
   print(number,"is not an Armstrong number")

Output

54748 is an Armstrong number 

Explanation

  • The code checks if the number (54748) is an Armstrong Number.
  • It calculates the sum of each digit raised to the power of the number of digits (order).
  • If this sum matches the original number, it prints that it is an Armstrong Number; otherwise, it indicates that it is not.
Read More: While Loop in Python

4. Check the Armstrong number of n digits using functions

# Function to calculate x raised to the power y
def power(a, b):	
	if b == 0:
		return 1
	if b % 2 == 0:
		return power(a, b // 2) * power(a, b // 2)		
	return a * power(a, b // 2) * power(a, b // 2)
# Function to calculate the order of the number
def order(a):
	# Variable to store the number
	n = 0
	while (a != 0):
		n = n + 1
		a = a // 10		
	return n
# Function to check whether the given number is an Armstrong number or not
def isArmstrong(a):	
	n = order(a)
	temp = a
	sum1 = 0	
	while (temp != 0):
		r = temp % 10
		sum1 = sum1 + power(r, n)
		temp = temp // 10
	# If condition satisfies
	return (sum1 == a)
# Driver code
a = 370
print(isArmstrong(a))
a = 1253
print(isArmstrong(a))    

Output

True
False

Explanation

  • In the above code, power(a, b) is a recursive function that calculates the power of a number a raised to the exponent b.
  • The order(a) function calculates the order of a number, i.e., the number of digits in it, whereas the Armstrong (a) function checks if the number a is an Armstrong number by summing the powers of its digits and comparing it to the original number.
Read More: Python Functions

5. Check Armstrong number of n digits using Recursion

def getSum(num):
    if num == 0:
        return num
    else:
        return pow((num % 10), order) + getSum(num // 10)  
num = 371
# Order of the input
order = len(str(num))
# Call the function
sum_val = getSum(num) 
if sum_val == num:
    print('It is an Armstrong number')
else:
    print('It is not an Armstrong number') 

Output

It is an Armstrong number

Explanation

  • The code uses a recursive function (getSum) to check if a number is an Armstrong Number.
  • It calculates the sum of each digit raised to the power of the total number of digits (order).
  • If this sum matches the original number, it prints that it is an Armstrong Number; otherwise, it indicates that it is not.

6. Check Armstrong Number Using List Comprehension

# Function to check if a number is an Armstrong number using list comprehension
def is_armstrong(num):
    """
    Function to check whether a given number is an Armstrong number.
    :param num: Integer number to check
    :return: True if the number is Armstrong, False otherwise
    """
    power = len(str(num))  # Get the number of digits
    return num == sum(int(digit) ** power for digit in str(num))  # List comprehension
# Driver code
if __name__ == "__main__":
    # Test cases
    numbers = [153, 9474, 370, 1253]
    for num in numbers:
        print(f"{num} is Armstrong: {is_armstrong(num)}")    

Output

153 is Armstrong: True
9474 is Armstrong: True
370 is Armstrong: True
1253 is Armstrong: False

Explanation

  • Function Definition: Compares the original number with the sum of its digits raised to the power of its length.
  • List Comprehension: Efficiently computes the required sum in one line.
  • Driver Code: Ensures code runs only when executed directly.
  • Output Logic: Iterates through the list and prints the Armstrong status.
Read More: List Comprehension in Python

7. Check Armstrong Number Using map() and lambda

# Function to check if a number is an Armstrong number using map() and lambda
is_armstrong = lambda num: num == sum(map(lambda x: int(x) ** len(str(num)), str(num)))
# Driver code
if __name__ == "__main__":
    # Test cases
    numbers = [407, 9475]
    for num in numbers:
        print(f"{num} is Armstrong: {is_armstrong(num)}")    

Explanation

  • Lambda Function:The inline function checks the Armstrong number.
  • map() Usage: Raises each digit to the power of digit count.
  • sum() Function: Adds the powered digits.
  • Conditional Check: Compares the sum with the original number.

Output

407 is Armstrong: True
9475 is Armstrong: False
Read More:

8. Python program to check if a number is an Armstrong number without using the power function

An Armstrong number (or narcissistic number) is a number where the sum of its digits raised to the power of the number of digits equals the original number. We can determine this without using the power() function by manually multiplying the digit n times in a loop.

  • Manual Exponentiation: Instead of using pow(), we use a loop to multiply the digit by itself n times.
  • Efficient Calculation: The function iterates through the digits and computes the sum using basic arithmetic, avoiding recursion.
def isArmstrong(num):	n = num
	numDigits = 0
	sum = 0	
	# Find number of digits in num
	while n > 0:
		n //= 10
		numDigits += 1	
	n = num	
	# Calculate sum of digits raised to the power of numDigits without using pow()
	while n > 0:
		digit = n % 10
		power = 1		
		# Compute digit^numDigits manually
		for _ in range(numDigits):
			power *= digit		
		sum += power
		n //= 10	
	# Check if num is Armstrong number or not
	if sum == num:
		return True
	return False
num1 = 407
if isArmstrong(num1):
	print(num1, "is an Armstrong number.")
else:
	print(num1, "is not an Armstrong number.")
num2 = 372
if isArmstrong(num2):
	print(num2, "is an Armstrong number.")
else:
	print(num2, "is not an Armstrong number.")

Output

407 is an Armstrong number.
372 is not an Armstrong number.

Explanation

In this example;

  • The function first counts how many digits are in the number by dividing it by 10 again and again in a loop.
  • Then it goes through each digit, manually calculates the digit raised to the power of the number of digits (without using pow()), and adds all those results.
  • Finally, it checks if this total sum is equal to the original number. If yes, it's an Armstrong number; otherwise, it's not.

9. Python program to check if a number is an Armstrong number Using string manipulation

You can check if a number is an Armstrong number using string manipulation by converting the number into a string to extract its digits. Then, we raise each digit to the power of the total number of digits and sum the results.

  • String Conversion: Convert the number to a string to easily extract each digit.
  • List Comprehension for Calculation: Use a compact one-liner to compute the sum of each digit raised to the required power.

def isArmstrong(num):
    num_str = str(num)  # Convert number to string
    numDigits = len(num_str)  # Count the number of digits
    
    # Compute sum of digits raised to the power of numDigits
    total = sum(int(digit) ** numDigits for digit in num_str)
    
    # Check if num is an Armstrong number
    return total == num

num1 = 153
if isArmstrong(num1):
    print(num1, "is an Armstrong number.")
else:
    print(num1, "is not an Armstrong number.")

num2 = 123
if isArmstrong(num2):
    print(num2, "is an Armstrong number.")
else:
    print(num2, "is not an Armstrong number.")

Output

153 is an Armstrong number.
123 is not an Armstrong number.

Explanation

In this example;

  • The function first converts the number to a string to easily count the digits using len().
  • Then it uses a one-line sum() with a loop to add each digit raised to the power of the total number of digits.
  • Finally, it compares the total with the original number and returns True if they are equal, meaning it is an Armstrong number.

Practical Examples and Use Cases of Armstrong Number

Let's learn some of the most important practical examples and use cases of Armstrong numbers.

  • Error Detection: Armstrong numbers can be used in error detection techniques, especially in data transmission and storage systems, where ensuring data integrity is crucial.
  • Security: Armstrong numbers can serve as part of encryption keys or hash functions, enhancing security measures by introducing complexity and randomness into cryptographic systems.
  • Data Analysis: Armstrong numbers can be used as keys in databases or as markers in datasets to categorize or filter data based on specific criteria.
  • Testing Algorithms: Armstrong numbers provide a useful benchmark for testing and evaluating algorithms, especially those related to number theory and mathematical operations.
  • Performance Testing: Armstrong numbers can be utilized in performance testing scenarios to evaluate the computational efficiency of algorithms or systems.
  • Puzzle and Game Design: Armstrong numbers can be incorporated into puzzle and game design to create challenges or quests that require players to identify or generate Armstrong numbers.
Read More:

Armstrong Numbers in Different Number Systems

Armstrong numbers are used in various number systems. Let's go through some of them.

1. Armstrong Numbers in Binary

  • Convert the number to binary format.
  • Extract each binary digit and count the total digits.
  • Calculate the sum of each digit raised to the power of the total digits.
  • If the sum matches the original number, it is an Armstrong number in binary.

2. Armstrong Numbers in Octal

  • Convert the number to octal format.
  • Extract the octal digits and count them.
  • Compute the sum of each digit raised to the power of the total number of digits.
  • If the sum equals the original number, it is an Armstrong number in octal.

3. Armstrong Numbers in Hexadecimal

  • Convert the number to hexadecimal format.
  • Extract each hexadecimal digit and determine the total number of digits.
  • Calculate the sum of each digit raised to the power of the total digits.
  • If the computed sum matches the original number, it is an Armstrong number in hexadecimal.
Conclusion

In conclusion, an Armstrong number in Python is a number that equals the sum of its digits raised to the power of the number of digits. It’s a simple way to practice number logic and loops. Learning to check an Armstrong number in Python helps improve basic coding skills.

If you are preparing for the Python Interview Questions and Answers Book, this Python Interview Questions and Answers Book can really help you. It has simple questions and answers that are easy to understand. Download and read it for free today!

Boost your Python knowledge with this fun quiz!

Dear learners, challenge yourself and see how much you know by attempting this quiz!

Q 1: What is the correct file extension for Python files?

  • .pt
  • .pyt
  • .py
  • .pyth

FAQs

A positive number where the sum of its digits each raised to the power of the number of digits equals the number itself is known as an Armstrong number.

Yes, 371 is an Armstrong number.

153 = 1*1*1 + 5*5*5 + 3*3*3

To find Armstrong numbers between 1-500 in Python, you can use a loop to iterate through each number in the range and check if it satisfies the Armstrong number condition.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Live Training - Book Free Demo
Azure AI Engineer Certification Training
21 Jun
β€’
05:30PM - 07:30PM IST
Checkmark Icon
Get Job-Ready
β€’
Certification
Accept cookies & close this