Armstrong Number in Python using Recursion

Write a recursive function in Python which takes one integer as function argument and checks whether the number is Armstrong Number or not.

Definition: An Armstrong Number is any number of N digits which is equal to the sum of Nth power of digits in the number.

Generally in most programming cases, we consider numbers from 0 to 999, i.e. 3-digit numbers. Thus, we also define an Armstrong number as any number of three digits as the sum of the cubes of digits in a given number.

Example:
3-digit Armstrong Number = 153 because 13 + 53 + 33 = 153.
4-digit Armstrong Number = 1634 because 14 + 64 + 34 + 44 = 1634.

num = int(input("Enter the number: "))
size = len(str(num))
sum = 0
def isArmstrong(n):
    global sum
    global num
    global size
    if n < 10:
        sum += n ** size
        return num == sum
    else:
        sum += (n % 10) ** size
        return isArmstrong(n // 10)
if isArmstrong(num):
    print(str(num) + " is an Armstrong Number.")
else:
    print(str(num) + " is NOT an Armstrong Number.")

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.