Python | Check if a number is an Armstrong Number or not without using Recursion

Let us take a look at some methods using which we can solve this problem. Some of the methods that we are going to see are by using functions, loops, etc

Method 1: Using the function

def is_armstrong_or_not(num,n1,sum,temp):
    if temp==0:
        if sum==num:
            return True
        else:
            return False
    digit = temp % 10
    sum = sum + digit**n1
    temp = temp//10
    return is_armstrong_or_not(num, n1, sum, temp)

num = int(input("Enter a number to check if it is an Armstrong number or not: "))
sum = 0
n1 = len(str(num))
temp = num
res = is_armstrong_or_not(num,n1,sum,temp)

if res:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Output:

Enter 3-digit number to find if it is an Armstrong number or not: 9474
9474 is not an Armstrong number

Enter 3-digit number to find if it is an Armstrong number or not: 153
153 is an Armstrong number

Explanation:

Here we check the number if it is an Armstrong number or not using the while loop. We declared three variables sum, temp and n1, where the value in sum is 0 and in temp, it is the value in num. In n1 we store the length of the value in the num variable that is converted to a string. We used the while loop by adding a condition temp > 0, if yes then we perform the modulo operation that is temp%10 and store the value in the digit variable. Now we add the value in sum with that of digit *n1 and finally perform the floor division of temp.

Method 2: Using the pow() function

def calc_power(x, y):
    if y == 0:
        return 1
    if y % 2 == 0:
        return calc_power(x, y // 2) * calc_power(x, y // 2)
    return x * calc_power(x, y // 2) * calc_power(x, y // 2)
 
def check_order(x):
    n = 0
    while (x != 0):
        n = n + 1
        x = x // 10
    return n

def check_armstrong(x):
    n = check_order(x)
    temp = x
    sum = 0
 
    while (temp > 0):
        rem = temp % 10
        sum = sum + calc_power(rem, n)
        temp = temp // 10
    return (sum == x)
 
x = int(input("Enter n-digit number to check if it an  Armstrong number or not: "))
 
print(check_armstrong(x))

Explanation:

Here we defined separate functions for each operation that needs to be performed. Initially, we called the check_armstrong function, in which the operations performed are similar to the previous method but here to calculate the power we called a different function. The values are then passed on to the calc_power function. From the check_armstrong function, we have also called the check_order function that adds n and 1 and then performs floor division.

Here is the end of our article on Python Programs to check if a number is an Armstrong Number or not without using Recursion. We learned two ways by which we can solve this problem without the use of recursion.

Share:

Author: Ayush Purawr