A program to find out a number is disarium number or not
Answers
Examples:
Input : n = 135 Output : Yes 1^1 + 3^2 + 5^3 = 135 Therefore, 135 is a Disarium number
import java.util.*;
class disarium_number//class name
/* A disarium number is a number whose digits are taken to the power of the number of digits
* counted from the start and the addition of all the powers is equal to that number.
* For example,135 is a disarium number because 1^1+3^2+5^3=1+9+125=135.
* So inorder to determine whether a number is disarium or not, you would have to count the
* digits of the particular number taken as input from the user.Then we have to perform
* digit extraction and the last digit will be powered by the total number of digits.
* Then the total digits are subtracted by 1.
* To make it clear, 135:
* First we count the digits. There are 3 digits.
* Now perform digit extraction to obtain the last digit=5.
* Now do Math.power(5,number of digits),that is(5,3);
* So 5 is cubed =125.
* Then perform 3--.(Digits are subtracted by 1)=2.
* Next 2 is taken to the power of 3 because 3 is the last digit due to extraction of digits.
* So 3^2 is 9.
* Lastly, the digits when subtracted by 1 becomes 2-1= 1.
* The last digit for extraction is 1.
* So 1^1=1.
* All these powers are finally added.
* If sum is equal to the number,it is disarium else not disarium.
* For example 125+9+1=135.So the output will be disarium number.
*/
{
public void main()//calling the main function
{
Scanner sc=new Scanner(System.in);//Scanner class declaration
System.out.println("Enter a number to check whether a number is disarium or not");
/*This output will appear and the user must enter an integer otherwise input
* mismatch exception error will take place.
*/
int n=sc.nextInt();//the number input taken by the user.
int d=0;
/*the last digit of the number will be obtained by finding the remainder
of the number by dividing it by 10.*/
int c=0;//to count the number of digits
int cpy1=n;// copy variable cpy1 is taken as the value of the number(n) changes
while(n>0)
{
d=n%10;//last digit of n
c++;//c is added for each digit untill ultimately there is no more digits
n=n/10;//value of n changes so cpy1=n is taken
}
int cpy2=cpy1;//another copy variable is taken as value of cpy1 changes
double s=0.0;//double s will find the sum
while(cpy1>0)
{
d=cpy1%10;
s=s+Math.pow(d,c);//for finding the sum of all powers
c--;//the number of digits is subtracted for each powers
cpy1=cpy1/10;//value of cpy1 changes and so cpy2=cpy1 is taken
}
if(s==cpy2)
{
System.out.println("Disarium number");
/*prints disarium if sum of all the powers
*is equal to the number
for example 135*/
}
else
{
System.out.println("Not a disarium number");
}
}
}
The comments represented by /* explains everything .