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.")

2 thoughts on “Armstrong Number in Python using Recursion

  1. Sir,a program is given which states that:
    WAP in Java to accept a number and check whether it is Ore number or not.

    Ore numbers are positive integers whose divisors have a integer harmonic value. Ore numbers are often called as harmonic divisor number.
    For example, 6 has four divisors namely 1, 2, 3 and 6.
    Harmonic mean of the divisors is:
    4/(1+1/2+1/3+1/6)=2

    The harmonic mean of divisors of 6 is 2, an integer. So, 6 is an Ore number or harmonic divisor number.

Leave a Reply

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