How to Find an Armstrong Number Using Python

How to Find an Armstrong Number Using Python

6 mins read27.5K Views Comment
clickHere
Updated on Jan 18, 2024 12:17 IST

An Armstrong number (also called a narcissistic number) is an integer 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 because 153 = 13 + 53 + 33. Python provides different methods to check whether the given number is an Armstrong number or not. In this article, we will explore these methods with the help of examples.

2022_06_Feature-Image-Templates-72.jpg

Table of Content

What is an Armstrong Number?

First, let us ensure that we all have a good idea of an Armstrong number. It is a positive integer where the sum of each digit powered with the total number of digits equals the number itself. 

In other words, a number with n digits is called an Armstrong number of order n, where the sum of each digit powered by n is the same as the number. For example,

2022_06_image-163.jpg
2022_06_image-165.jpg
2022_06_image-178.jpg

All numbers exhibiting this sum property are called Armstrong numbers. They are also known as narcissist numbers.

Now, let’s see how we determine whether a given number is a narcissist:

Methods to Find an Armstrong Number Using Python

For 3-digit numbers (using while loop)

The most common examples for Armstrong numbers are usually three-digit numbers, and hence, first, we will write a program specifically for 3-digit integers:


 
#Enter input
num = int(input("Enter 3-digit number : "))
sum = 0
temp = num
#Define a function
while temp > 0:
digit = temp % 10
sum += digit * digit * digit
temp = temp//10
if sum==num:
print('It is an Armstrong number')
else:
print('It is not an Armstrong number')
Copy code

Output 1:

2022_06_image-168.jpg

Output 2:

2022_06_image-176.jpg

What have we done here?

  • In the above code again, to check if the 3-digit input is an Armstrong number or not, we will first declare a variable sum and initialize it to 0.
  • Next, we run the while loop which calculates the sum of the cube of each digit. This sum is obtained by using the modulus operator %. The remainder of the input number when divided by 10 gives us the last digit of that number.
  • Then, we check if the sum is equal to the input number:
    • if yes, it is an Armstrong number.
    • else, it is not.
Armstrong Number in C
Armstrong Number in C
An Armstrong Number is defined as the sum of the nth power of each digit to an n-digit number that is equal to that number. Confused! Don’t worry. In this...read more
Armstrong Number in Java using Different Methods
Armstrong Number in Java using Different Methods
Learn to check if a number is an Armstrong number in Java using while loop or recursion. Understand the mathematical definition and see code examples for easy implementation
Top 9 NumPy Interview Questions
Top 9 NumPy Interview Questions
In this article, we will discuss basic and intermediate NumPy Interview Questions in most simplified ways with example.
Variables in Python
Variables in Python
In this article, we will discuss variables in python, how to name them and how to work with the variables.
Python Sets Practice Programs For Beginners
Python Sets Practice Programs For Beginners
Python offers a rich collection of sequence object types, and sets are one of them.

Also explore: Introduction to Python Data Types with Examples

  • In the above code, we declare three functions – 
  • The power() function takes two arguments – x and y. In the function body, it calculates x raised to the power y
  • The order() function calculates the order of the input number.
  • The isArmstrong() function checks whether the given input is an Armstrong number or not.
    • In the function body, we will run the while loop, which calculates the sum of the digits, where the order value powers each digit. 
    • If the condition satisfies, meaning the sum matches the input value, it is an Armstrong number so that the function will return True.

For n-digit numbers(using while loop)

Now, we can simply generalize the above program to find Armstrong numbers having n-digits, as shown:


 
#Enter input
num = int(input("Enter 3-digit number : "))
sum = 0
temp = num
#Define a function
while temp > 0:
digit = temp % 10
sum += digit * digit * digit
temp = temp//10
if sum==num:
print('It is an Armstrong number')
else:
print('It is not an Armstrong number')
Copy code

Output 1:

2022_06_image-181.jpg

Output 2:

2022_06_image-171.jpg

What have we done here?

  • In the above code again, to check if the n-digit input is an Armstrong number or not, we will first declare a variable sum and initialize it to 0. 
  • Now, before running the loop, we will first calculate the order of the input number, i.e., the number of digits in the number. This value will be stored in the variable order
  • Next, we will run the while loop, which calculates the sum of the digits, where the order value powers each digit. 
  • Then, we check if the sum is equal to the input number:
  • If yes, it is an Armstrong number.
  • Else, it is not.

For n-digit numbers(using functions)

We can also determine if a positive integer is an Armstrong number by using functions in Python:


 
#Define a function to calculate x raised to the power y
def power(x, y):
if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)
return x * power(x, y // 2) * power(x, y // 2)
#Define a function to calculate order of the number
def order(x):
#Variable to store of the number
n = 0
while (x != 0):
n = n + 1
x = x // 10
return n
#Define a Function to check whether the given number is Armstrong number or not
def isArmstrong(x):
n = order(x)
temp = x
sum = 0
while (temp > 0):
rem = temp % 10
sum = sum + power(rem, n)
temp = temp // 10
#The while condition satisfies
return (sum == x)
#Enter input
x = int(input("Enter n-digit number : "))
print(isArmstrong(x))
Copy code

Output:

2022_06_image-172.jpg

What have we done here?

  • In the abIn the above code, we declare three functions – 
  • The power() function takes two arguments – x and y. In the function body, it calculates x raised to the power y
  • The order() function calculates the order of the input number.
  • The isArmstrong() function checks whether the given input is an Armstrong number or not.
  • In the function body, we will run the while loop, which calculates the sum of the digits, where the order value powers each digit. 
  • If the condition satisfies, meaning the sum matches the input value, it is an Armstrong number so that the function will return True.

For n-digit numbers(using recursion)

In this method, we find the Armstrong number by using recursion, which is a process where the function calls itself.


 
#Define a function
def getSum(num):
if num == 0:
return num
else:
return pow((num),order) + getSum(num//10)
#Enter input
num = int(input("Enter n-digit number : "))
#Order of the input
order = len(str(num))
#Call the function
sum = getSum(num)
if sum==num:
print('It is an Armstrong number')
else:
print('It is not an Armstrong number')
Copy code

Output:

2022_06_image-180.jpg

What have we done here?

  • The above code declares the getSum() function that accepts an integer argument – num
  • Which calculates the sum of the digits, where the order value powers each digit. 
  • The order value is the number of digits in the input number. This value will be stored in the variable order.
  • Then, we call the function recursively, and if the sum matches the input value, it is an Armstrong number. 

Endnotes

Armstrong number is just a number puzzle for beginner programmers to help them grasp the concepts with better understanding. They have no real-world applications as such. Hope this article was helpful for you to understand how to find an Armstrong number using Python.

Hello World Program in Python-A Beginner’s Guide
Hello World Program in Python-A Beginner’s Guide
Python is a powerful, widely used general-purpose, object-oriented, high-level programming language. It is one of the most popular coding languages due to its versatility. Python is often used for data...read more
Fibonacci Series in Python
Fibonacci Series in Python
Fibonacci Series is a sequence of numbers where each number is the sum of the two previous numbers. This article will discuss the Fibonacci Series, How to Create a Fibonacci...read more
Difference between Deep Copy and Shallow Copy in Python
Difference between Deep Copy and Shallow Copy in Python
In this article you will find the difference between deep copy and shallow copy in python with programming examples. It also includes advantages and disadvantages.
Python NumPy Tutorial: For Beginners
Python NumPy Tutorial: For Beginners
This article talks about NumPy. How to install it? It also covers Input/Output, creating and Manipulating DataArray Operations, mathematical and statistical Functions with NumPy, You will learn reshaping, Joining, and...read more
Difference Between List and Set
Difference Between List and Set
In this article, we will briefly cover what lists and sets are in Java and Python, the difference between them, and the features of lists and sets.
Building a GUI Desktop Calculator Using PyQt
Building a GUI Desktop Calculator Using PyQt
Python is the most commonly used programming language across the world. It is an object-oriented, interpreted, and general-purpose programming language. It can be used to make web applications, system automation,...read more
Pandas vs Dask -Which One is Better?
Pandas vs Dask -Which One is Better?
Find the main differences between Pandas and Dask.
Understanding splitlines() Function in Python
Understanding splitlines() Function in Python
This blog explains Spiltlines() function in Python. We have explained this concept with the help of example. Let’s understand!
Password Generator in Python
Password Generator in Python
This is a quick guide for those who want to generate strong password using python. This article includes step by step explanation of programming and included all steps needed to...read more
Using Excel Spreadsheets in Python
Using Excel Spreadsheets in Python
Excel spreadsheets are a popular tool for data analysis, but what if you want to manipulate and analyze that data using Python? Luckily, there’s a library called openpyxl that allows...read more
Rename Method: Renaming Files in Python
Rename Method: Renaming Files in Python
Python is a popular and versatile programming language that is used in a wide variety of applications, from web development to scientific computing. One of its most useful features is...read more
Understanding isdecimal() Method in Python
Understanding isdecimal() Method in Python
This blog explains isdecimal() function in Python. We have explained this topic with the help of relevant examples.
Understanding isalnum() Method in Python
Understanding isalnum() Method in Python
This blog explains isalnum() Method in Python with the help of examples. Let’s explore!
All About isdigit() Method in Python
All About isdigit() Method in Python
This blog explains isdigit() method in Python. We have explained this concept with the help of examples. Let’s explore!
What is Partition() Function in Python?
What is Partition() Function in Python?
This blog explains Partition() Function in Python with the help of example. Let’s understand!
Python Dependency Management Made Simple
Python Dependency Management Made Simple
Here you will understand dependency management in Python, its importance and its tools. Let’s explore!
Exploring Python Pickle: The Ultimate Resource for Object Serialization and Storage
Exploring Python Pickle: The Ultimate Resource for Object Serialization and Storage
In this article, we will briefly discuss how to use the Python pickle module with the help of examples. We will also discuss some of the best practices for using...read more
Types of Functions in Python
Types of Functions in Python
This article explains different types of Functions in Python.The functions explained are Built-in Functions, User-defined Functions, Recursive Functions, Lambda Function.

FAQs

What is an Armstrong number?

An Armstrong number is a number that is equal to the sum of the cubes of its own digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Can you check for Armstrong number for negative or decimal numbers?

Armstrong number is only defined for positive integers, So, you cannot check for negative or decimal numbers.

How to check Armstrong number for a large number?

The logic is the same as with small numbers, but you need to use a larger data type like long or BigInteger to hold the large number and result of the cubing and summing.

Is it necessary to check for the length of the input number?

Yes, it is necessary to check for the length of the input number, because the length of the input number is used to calculate the sum of cubes of the digits of the number.

What is a Simple Python Code to Check for Armstrong Numbers?

A basic Python code to check for Armstrong numbers includes:

  • Taking an input number.
  • Calculating the length of the number.
  • Summing the digits raised to the power of the length.
  • Comparing the sum with the original number to determine if it's an Armstrong number

Can You Implement Armstrong Number Check Using a Function in Python?

Yes, you can create a function to check for Armstrong numbers. This function will:

  • Calculate the power of each digit according to the number of digits.
  • Sum these powers.
  • Compare the sum with the original number to confirm if it's an Armstrong number

What are the Armstrong Numbers Between 1 and 100?

The Armstrong numbers between 1 and 100 are all single-digit numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, as each digit raised to the power of 1 equals the number itself.

Are There Alternate Methods to Check Armstrong Numbers in Python?

Yes, apart from using a while loop, you can also use:

  • A for loop for a more concise code structure.
  • A recursive function for a different coding approach.
  • List comprehension for a compact solution.
  • Generators for optimizing memory usage with large numbers
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio