Python Program For Armstrong Number

How to Write Python Program For Armstrong Number Using While Loop, For Loop, Functions, and Recursion? We also show you the Python program to print Armstrong Numbers between 1 to n.

Python Armstrong Number

If the given number equals the sum of the Nth power of each digit present in that integer, then that can be an Armstrong—for example, 370.

Individual digits in 370 = 3

370 = 3³ + 7³ + 0³ = 27 + 343 + 0 = 370

Python Program For Armstrong Number Algorithm Steps:

The below steps show you the common approach to checks for the Armstrong Number.

  1. The user has to enter any number.
  2. Count the total individual digits (For Example, 370 means 3).
  3. Divide the given integer into individual digits (For Example, Divide 370 into 3, 7, and 0).
  4. Calculate the power of n for each individual and add them.
  5. Compare the original value with the Sum value.
  6. If they exactly matched, then it is an Armstrong. Else, it is not.

Python Program for Armstrong Number Using While Loop

This program allows the user to enter any positive integer. And then, this Python program code checks whether a number is Armstrong or Not using the While Loop.

# Using While Loop
Number = int(input("Please Enter the Number to Check: "))

Sum = 0
Times = 0

Temp = Number
while Temp > 0:
    Times = Times + 1
    Temp = Temp // 10

Temp = Number
while Temp > 0:
    Reminder = Temp % 10
    Sum = Sum + (Reminder ** Times)
    Temp //= 10

if Number == Sum:
    print("%d is Armstrong." %Number)
else:
    print("%d is Not." %Number)
Python Program for Armstrong Number Using While Loop

This program for Armstrong number in Python code allows the user to enter any positive integer and then assign it to a variable.

Next, We assign the original value to the Temp variable. It helps to preserve our original value and then do all the manipulation on the Temp variable.

The first While Loop makes sure that the given number is greater than 0. Statements inside the while loop split it and count the individual digits inside the given integer. If you don’t understand the program logic, Please refer to the Find Total Digits article in Python.

The Second While loop of the Armstrong Number in Python program ensures that the given integer is greater than 0. Let us see the working principle of this while loop in iteration wise

while Temp > 0: Reminder = Temp % 10 Sum = Sum + (Reminder ** Times) Temp //= 10

User Entered value for this Python Program For Armstrong Number = 9474 and Sum = 0

Temp =Number
Temp = 9474

First Iteration

Reminder = Temp %10
Reminder = 9474 % 10 = 4

Sum = Sum + pow (Reminder, Times)

For this Python Program For Armstrong Number example, Times =4 because the total digits in 9474 = 4. So,

Sum = 0 + (4 * 4 * 4 * 4) => 0 + 256 => Sum = 256

Temp = Temp /10 => 9474 /10
Temp = 947

NOTE: If the digits count is 5, then Reminder multiplied by 5 times.

Second Iteration: From the Python Program to check Armstrong Number first iteration, the values of both Temp and Sum changed as Temp = 163 and Sum = 256.

Reminder = 947 % 10 = 7

Sum = 256 + (7 * 7 * 7 * 7) => 256 + 2401
Sum = 2657

Temp = 163 /10 = 94

Third Iteration: From the second iteration, the values of Temp = 94 and Sum = 2657.

Reminder = 94 % 10 = 4

Sum = 2657 + (4 * 4 * 4 * 4) => 2657 + 256
Sum = 2913

Temp = 94 /10 = 9

Python Program For Armstrong Number Fourth Iteration: From the third Iteration, the values of Temp = 9 and Sum = 2913

Reminder = 9 % 10 = 0

Sum = 2913 + (9 * 9 * 9 * 9) => 2913 + 6561
Sum = 9474

Temp = 9/10 = 0

Here Temp = 0, so the while loop condition fails.

if(9474 == 9474), Condition checks whether the user entered is exactly equal to Sum. If this condition is True, then it is; else, it is not.

NOTE: If you are finding the number below 1000, remove the while loop to count the digits in an integer, and then replace the below code

Sum = Sum + (Reminder ** Times);

With

Sum = Sum + (Reminder * Reminder * Reminder)

To avoid the first while loop, in this Python code for Armstrong, we used the str() function to convert the number to a string, and the len() function to find the total digits.

Num = int(input("Enter the Value : "))

numText  = str(Num)
l = len(str(Num))

Sum = 0

Temp = Num
while Temp > 0:
    Reminder = Temp % 10
    Sum = Sum + (Reminder ** l)
    Temp //= 10
Enter the Value : 8208
8208 is Armstrong.

Armstrong Number in Python using For Loop Program

This Python program allows the user to enter any positive integer and then checks whether a number is Armstrong or Not using For Loop.

# Using For Loop
Num = int(input("\nPlease Enter the Value : "))

Sum = 0
Times = 0
           
Temp = Num
while Temp > 0:
    Times = Times + 1
    Temp = Temp // 10

Temp = Num
for n in range(1, Temp + 1):
    Reminder = Temp % 10
    Sum = Sum + (Reminder ** Times)
    Temp //= 10

if Num == Sum:
    print("\n %d is Armstrong Number.\n" %Num)
else:
    print("\n %d is Not.\n" %Num)

We replaced the While loop in the above example with the For loop. If you don’t understand the for loop, then please refer to the For Loop article.


Please Enter the Value : 371

 371 is Armstrong Number.



Please Enter the Value : 4458

 4458 is Not.

If we convert the number to a string, the len() functions will get the total number of digits and the for loop reads each digit as a character. So, we can avoid an extra while loop, finding the remainder, and removing the last digit from a number.

Num = int(input("\nPlease Enter the Value : "))

numText  = str(Num)
l = len(numText)

Sum = 0

for n in numText:
    Sum = Sum + int(n) ** l

if Num == Sum:
    print("\n %d is Armstrong Number.\n" % Num)
else:
    print("\n %d is Not.\n" % Num)
Please Enter the Value : 407

 407 is Armstrong Number.

Python Program for Armstrong Number using List Comprehension

In this Python example code, we used the list comprehension and math log10 function to check the Armstrong number.

  • digits = [int(i) for i in str(num)] – We used the list comprehension to read each individual digit and create a list of those digits.
  • Use either len(digits) or int(math.log10(num)). Both will return the total digits.
  • sum([d ** length for d in digits]) – It will calculate the power of length(total digits) for each individual. The sum()function calculates the list sum.
import math

num = int(input("Enter a number: "))

digits = [int(i) for i in str(num)]

#length =len(digits)
length = 1 + int(math.log10(num))

sum = sum([d ** length for d in digits])

if num == sum:
   print(num,"is an Armstrong number.")
else:
   print(num,"is not.")
Enter a number: 9992
9992 is not.

Enter a number: 8208
8208 is an Armstrong number.

Python Program to Check Armstrong Number using Functions

This Python program allows users to enter any positive integer and checks whether a number is Armstrong or Not using Functions.

# Using Functions
def ArmFind(val):
    total = 0
    Times = 0

    # Calculating individual digits
    tm = val
    while tm > 0:
        Times = Times + 1
        tm = tm // 10


    tm = val
    for n in range(1, tm + 1):
        Reminder = tm % 10
        total = total + (Reminder ** Times)
        tm //= 10
    return total


#User Input
val = int(input("Please Enter to Find : "))

if (val == ArmFind(val)):
    print("\n%d is Armstrong Number." %val)
else:
    print("\n%d is Not." %val)

Please Enter to Find : 153

 153 is Armstrong Number.

>>> 

Please Enter to Find : 2256

 2256 is Not.

In this Python Program For the Armstrong Number example, we defined the following function to perform all the necessary calculations and return Sum.

def ArmFind(val):

When the compiler reaches the following code inside the If statement, then the compiler immediately jumps to the above-specified function.

ArmFind(val)

We have already explained the LOGIC above example.

Python Program to Check Armstrong Number using Recursion

It allows us to enter any positive integer. Next, this Python program checks whether a number is Armstrong or Not using the recursion or recursive function concept.

# using Recursive functions
total = 0
Times = 0

def Count_Of_Digits(value):
    global Times
    if(value > 0):
        Times = Times + 1
        Count_Of_Digits(value // 10)
    return Times

def ArmFind(value, Times):
    global total
    if(value > 0):
        Reminder = value % 10
        total = total + (Reminder ** Times)
        ArmFind(value //10, Times)
    return total

value = int(input("Please Enter the value : "))

Times = Count_Of_Digits(value)
total = ArmFind(value, Times)
if (value == total):
    print("\n%d is Armstrong Number." %value)
else:
    print("\n%d is Not." %value)

Please Enter the Value : 153

 153 is Armstrong Number.

>>> 

Please Enter the Value : 259

 259 is Not.

In this Python Armstrong number program example, we defined two recursive functions. The following function accepts integer values as parameter values and counts the total individual digits in an integer recursively.

def Count_Of_Digits(value):

The following function accepts two integer values as parameter values. And it performs all the necessary calculations and returns the Sum.

def ArmFind(value, Times):

The following Statement in this Python Program For Armstrong Number helps to call the function Recursively with an updated value. If you miss this statement, it will terminate after completing the first line. For example,

ArmFind(value//10, Times)

Number= 153

Then the output = 27

Let’s see the If statement inside the above-specified functions

if (value > 0) checks whether the given value is greater than 0. For Recursive functions, placing a condition before using the function recursively is essential. Otherwise, we end up in infinite execution (Same as an infinite Loop).

Python Program to Find Armstrong Numbers between the 1 to n

This program allows you to enter minimum and maximum. And then, this Python program finds and returns Armstrong Numbers between the Minimum and Maximum values.

The first two statements present in this program allow the user to enter the minimum and maximum values.

The for Loop helps to iterate between Minimum and Maximum Variables. Iteration starts at the Minimum, and then it won’t exceed the Maximum variable.

if(n == tot) -– condition, check whether the sum of the power N for each digit present in that integer is equal to a given Value. When the condition is True, it is else it is not.

If this condition is True, then it prints that integer as a result.

Minimum = int(input("Please Enter the Minimum : "))
Maximum = int(input("\nPlease Enter the Maximum : "))

for n in range(Minimum, Maximum + 1):
    tot = 0
    Times = 0
           
    tp = n
    while tp > 0:
        Times = Times + 1
        tp = tp // 10

    tp = n
    while tp > 0:
        Rem = tp % 10
        tot = tot + (Rem ** Times)
        tp //= 10
    if n == tot:
        print(n)

The Python program for Armstrong numbers lists from 10 to 10000 output.

Please Enter the Minimum : 10

Please Enter the Maximum : 10000
153
370
371
407
1634
8208
9474

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.