Question
Check whether a number is an Armstrong number using recursion
A positive number is called an Armstrong number if sum of its own digits each raised to the power of the number of digits is equal to number
153
1^3+5^3+3^3=1+125+27=153
153 is an armstrong number
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class ArmstrongNumber
{
public static int SumOfDigit(int num,int i)
{
if(num==0)
{
return 0;
}
else
{
return (int)Math.pow(num%10,i)+SumOfDigit(num/10,i);
}
}
public static void main()
{
int num=0,sum=0,noOfDigits=0;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
num=sc.nextInt();
noOfDigits=Integer.toString(num).length();
sum=SumOfDigit(num,noOfDigits);
if(sum==num)
{
System.out.println(num+" IS AN ARMSTRONG NUMBER");
}
else
{
System.out.println(num+" IS NOT AN ARMSTRONG NUMBER");
}
}
}
Python
def sumOfDigits(num):
if(num<=0):
return 0
else:
digit=num%10
return digit**totalDigits+sumOfDigits(num//10)
#Main Method Starts from here
if(__name__=='__main__'):
number=int(input("Enter the number:"))
totalDigits=len(str(number))
"""
str(number) converted integer to string
len() gives length of string
so len(str(number)) combined gives total number of digits
"""
sum=sumOfDigits(number)
if(sum==number):
print(number,"IS AN ARMSTRONG NUMBER")
else:
print(number,"IS NOT AN ARMSTRONG NUMBER")