codingstreets
Search
Close this search box.

Python Program: Find Armstrong Number in Python

In this article, learn what Armstrong numbers are, how they work, and how to implement an efficient algorithm to identify them.

Let’s check out another Python project.

Table of Contents

Armstrong Number

A number is Armstrong Number, if each digit power is raised to the total number of digits in the number and the addition of them returns the original number known as the Armstrong number, otherwise not.

E.g., number = 153

total_digits = 3

Each digit power is raised to the total number of digits

1**3 = 1,       5**3 = 125,       3**3 = 27 

result = 1+125+27 = 153

Now, since the result = original number, therefore it is Armstrong Number.

Let’s take another example –

E.g., number = 123

total_digits = 3

Each digit power is raised to the total number of digits

1**3 = 1,       2**3 = 8,       3**3 = 27 

result = 1+8+27 = 36

Now, since the result is not equal to the original number, therefore it not is Armstrong Number.

Using for loop

Example: Using for loop.

				
					#num = 153
num = int(input("Enter the number: "))
digits = len(str(num))

total = 0
for number in str(num):
    sum = int(number) ** digits 
    total = total+sum  

if total == num:
    print(num, "is Armstrong number.")
else:
    print(num, "is not Armstrong number.")
				
			

Note: If you want the number already defined, uncomment the 1st line of code and comment on the 2nd line.

Explanation: 

The code starts with taking a number from the user by using the input() function and it is converted to an integer using int() and stored in the variable num.

The len() function is used to count the number of digits, from the variable num and stored the result in the variable digits.

The variable total is initialized to 0, which will hold the cumulative sum of each digit raised to the power of the number of digits.

The code then enters a for loop that iterates over each digit as a string representation of the number. In each iteration, the current digit is converted to an integer using int() and raised to the power of digits using the exponentiation operator **. The result is stored in the variable sum. This process is repeated for each digit in the number.

The calculated sum for each digit is added to the total variable.

After the loop completes, the code checks if the value of total is equal to the original num. If they are equal, it means the number is an Armstrong number, and the corresponding message is printed. Otherwise, the number is not an Armstrong number and a different message is printed.

Using range() function

Example: Using range() function.

				
					total = 0
for number in range(1, 10):  
    digits = len(str(number))  
    total = number**digits  

    if total == number:
        print(number, "is Armstrong number.")
    else:
        print(number, "is not Armstrong number.")
				
			

Explanation:

The variable total is initialized to 0, which will hold the cumulative sum of each digit raised to the power of the number of digits.

The code enters for loop that iterates over each digit within range. In each iteration, the current digit is counted and raised to the power of digits using the exponentiation operator **, and the result is stored in the variable total. This process is repeated for each digit in the number.

After the loop completes, the code checks if the value of total is equal to the original number. If they are equal, it means the number is an Armstrong number, and the corresponding message is printed. Otherwise, the number is not an Armstrong number and a different message is printed.

Using while loop – finite times

Example: Using while loop.

				
					n = 5
while n != 0:
    num = int(input("Enter the number: "))  
    digits = len(str(num))

    total = 0
    for number in str(num):
        sum = int(number) ** digits  
        total = sum + total  

    if total == num:
        print(num, "is Armstrong number.")
    else:
        print(num, "is not Armstrong number.")
    n -= 1
print("The task is done.")
				
			

Explanation:

The code repeatedly asks user to enter a number and checks whether each number is an Armstrong number or not. This process is repeated n times, where n is set to 5.

Within each iteration of the while loop, the user is asked to enter a number and stored it in the variable num.

The len() function is used to count the number of digits stored in the variable num.

The variable total is initialized to 0, which will hold the cumulative sum of each digit raised to the power of the number of digits.

The code enters for loop that iterates over each digit within range. In each iteration, the current digit is counted and raised to the power of digits using the exponentiation operator **, and the result is stored in the variable total. This process is repeated for each digit in the number.

The calculated sum for each digit is added to the total variable. 

After the loop completes, the code checks if the value of total is equal to the original number. If they are equal, it means the number is an Armstrong number, and the corresponding message is printed. Otherwise, the number is not an Armstrong number and a different message is printed.

The n variable is decremented by 1 in each iteration of the while loop. Once n becomes 0, the loop exits and the final message is printed.

Using while loop – Infinite times

Example: User decides whether the program continues or stops.

				
					while True:
    num = int(input("Enter the number: ")) 
    digits = len(str(num))

    total = 0
    for number in str(num):
        Sum = int(number) ** digits 
        total = Sum + total 

    if total == num:
        print(num, "is Armstrong number.")
    else:
        print(num, "is not Armstrong number.")

    ask_user = input("Do you want to check again? y/n --> ")

    if ask_user == "y":
        continue
    elif ask_user == "n":
        break

print("The task is done.")
				
			

Explanation:

The code explanation is as same as the above example except:

Since the while loop is True, means it does not stop until the user chooses to stop.

After checking the number once entered by the user, now a prompt appears to the user asking permission to continue or stop the program. If the user enters “y” the program continues and entered “n” the program stops using the break keyword.

Now, while loop is terminated and the print() function is used to display the message. 

Using def function

Example: Using def function

				
					def count_digits(num):
    global digits  # "global" used to access "digits" globally
    digits = len(str(num))  # len used to count the number of digits

    def total():
        total = 0
        for number in str(num):
            sum = int(number) ** digits
            total += sum

        if total == num:
            print(num, "is Armstrong number.")
        else:
            print(num, "is not Armstrong number.")

    # function called
    total()


# function called
count_digits(123)
				
			

Explanation:

First, we created a function count_digits() and passed a parameter num that takes an integer.

The function begins by declaring global variable digits that count the number of digits stored in variable num using the len function.

Next, a function total() is declared inside the function count_digits().

The for loop iterates over each number in variable num. It converts num to a string using str(num) and loops over each character in the resulting string.

In each iteration, the digit is converted to int using int(number) and raised the power to the total number of digits using the exponentiation operator **. The resulting value is stored in a variable called sum.

Now, the sum is added to the variable total, accumulating the sum of the individual digits raised to the power of digits.

After iterating all digits in the number, now for loop checks the conditional statement.

If the total == num, the function prints that num is an Armstrong number else num is not an Armstrong number.

Finally, the total function is called within the count_digits function to perform the calculations and determine whether the input number is an Armstrong number or not.

Conclusion

Armstrong numbers, also known as Narcissistic numbers, are equal to the sum of their digits raised to the power of the number of digits. 

In Python, we can implement an algorithm to identify Armstrong numbers efficiently. By iterating through the range of numbers and performing the necessary calculations, we can determine whether a given number is an Armstrong number or not.

So, dive into the world of Armstrong numbers in Python, and enjoy the process of unraveling the magic and beauty of numbers through code!

Recent Articles