Monday, January 19, 2015

Disarium Numbers Upto 2000 Using BlueJ Program




class Disarium
{
public void show()
{
int c,rev,sum,n,x;

for(int i=1;i<=2000;i++)
{
c=1;
 n=i;x=n;
sum=0;
rev=0;
while (n>0)
{
 rev=rev*10+n%10;
 n=n/10;
 }
 while(rev>0)
 {
  sum=sum+(int)Math.pow(rev%10,c);
  c++;
  rev=rev/10;
  }
  if(sum==x)
  System.out.println(x + " is DISARIUM");
 }
}

Related Post: What is Disarium Number

public static void main(String args[]) throws Exception
{
Disarium ob=new Disarium ();
ob.show();
}
}


How the Program is working


The numbers from 1 to 2000 are generated using the for loop for (int i=0;i<=2000;i++). The number is then reversed using a while loop and the reversed value is stored in variable 'rev'. The need of reversing the number is for getting the digits from left to right. (suppose the number is 124, 124%10 will give 4 but we need the left most digit '1' first so the number is reversed. 421%10 will give 1.). 'c' is a counter which is counting the position of each digit in the number - we are getting the value of 'c' as 1 for '1' of the number 124, 'c' as 2 for 2 of 124 and finally 'c' as 3 for 4 of 124 and value of 'c' is used as power of the respective digits of the number.

Related PostBlueJ Programs on Number

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner