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

def check_armstrong(num):
    if num == 0:
        return num
    else:
        return pow((num%10),order) + check_armstrong(num//10)

num = int(input("Enter a number to check if it is an Armstrong number or not: "))

order = len(str(num))  
sum = check_armstrong(num)

if sum == int(num):
    print(num,"is an Armstrong Number.")    
else:
    print(num,"is not an Armstrong Number.")

Output:

Enter a number to check if it is an Armstrong number or not: 1634
1634 is an Armstrong Number.

Explanation:

Here we passed the number to the function and we added a conditional statement to check if the number is zero then we directly return zero, otherwise, we used the power function to compute the value of (num%10), order, and added the computed value with the output of the check_armstrong function. This function is a number divided using floor division. Floor division simply rounds off the number to the nearest whole number. Finally, we passed on the result back.

Share:

Author: Dhvanil V