Question
Print Disarium number in a given range using recursion.
(A number is said to be the Disarium number when the sum of its digit raised to the power of their respective positions is equal to the number itself.)
11 + 72 + 53 = 1 + 49 + 125 = 175
ENTER THE LOWER RANGE
100
ENTER THE UPPER RANGE
500
135 175
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 disariumNumber
{
public static int CountDigits(long num,int count)
{
if(num==0)
{
return count;
}
else
{
count++;
return CountDigits(num/10,count);
}
}
public static long CalculateSum(long num,int totalDigits)
{
if(num==0)
{
return 0;
}
else
{
return (long)(Math.pow(num%10,totalDigits))+CalculateSum(num/10,totalDigits-1);
}
}
public static void main()
{
long lowerRange=0,upperRange=0,sum=0,i=0;
int FrequencyOfDigits=0;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE LOWER RANGE");
lowerRange=sc.nextLong();
System.out.println("ENTER THE UPPER RANGE");
upperRange=sc.nextLong();
for(i=lowerRange;i<=upperRange;i++)
{
FrequencyOfDigits=CountDigits(i,0);
sum=CalculateSum(i,FrequencyOfDigits);
if(sum==i)
{
System.out.print(i+" ");
}
}
}
}
Python
def countNumberDigits(n,count):
if(n==0):
return count
else:
count=count+1
return countNumberDigits(n//10,count)
def calculateSum(n,totalNumberOfDigits):
if(n==0):
return 0
else:
rem=n%10
return rem**totalNumberOfDigits + calculateSum(n//10,totalNumberOfDigits-1)
lowerRange=int(input("Enter lower value:"))
upperRange=int(input("Enter upper value:"))
print("Disarium number between",lowerRange,"and",upperRange,":")
for i in range(lowerRange,upperRange):
totalDigits=countNumberDigits(i,0)
sum=calculateSum(i,totalDigits)
if(sum==i):
print(i,end=" ")