Blog

How to check for a Disarium Number?

A Disarium number is something like this.

n=135

sum of digits= 11 + 32 + 53

If this sum of digits equals the original number n then it is a Disarium number.

 

Here is the code


package holyjava;

import java.util.Scanner;

public class Disarium {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
if(n==0)
{
System.out.println(n + " is Disarium");
return;
}
int count=0;
int copy=n;
while(copy>0)
{
count++;
copy=copy/10;
}

int sum=0;
copy=n;
while(copy>0)
{
int digit=copy%10;
copy=copy/10;
sum =sum + (int)Math.pow(digit, count);
count--;
}
if(sum==n)
{
System.out.println(n + " is Disarium");
}
else
{
System.out.println(n + " is not Disarium");
}
}
}

We make a copy of the n variable so that the original one doesn’t get modified.
the first loop calculates the no of digits in the integer.

    int count=0;
        int copy=n;
        while(copy>0)
        {
            count++;
            copy=copy/10;
        }

The next loop calculates the sum of the series.

   int sum=0;
        copy=n;
        while(copy>0)
        {
            int digit=copy%10;
            copy=copy/10;
            sum =sum + (int)Math.pow(digit, count);
            count--;
        }

The last if statement checks

   if(sum==n)
        {
            System.out.println(n + " is Disarium");
        }
        else
        {
            System.out.println(n + " is  not Disarium");
        }

Run it and enter 135
135
135 is Disarium

Try 134

134
134 is not Disarium

end

Leave a Reply

Your email address will not be published. Required fields are marked *