Disarium Number ISC 2016

A disarium number is a number in which the sum of the digits to the power of their respective position is equal to the number itself.

Example: 135 = 11 + 32 + 53
Hence, 135 is a disarium number.

Design a class Disarium to check if a given number is a disarium number or not. Some of the members of the class are given below:

Class name: Disarium
Data members/instance variables:
int num: stores the number.
int size: stores the size of the number.
Methods/Member functions:
Disarium(int n): parameterized constructor to initialize the data members num = n and size = 0.
void countDigit(): counts the total number of digits and assigns it to size.
int sumOfDigits(int n, int p): returns the sum of the digits of the number ‘n’ to the power of their respective positions ‘p’ using recursive technique.
void check(): checks whether the number is a disarium number and displays the result with an appropriate message.

Specify the class Disarium giving details of the constructor, void countDigit(), int sumOfDigits(int, int) and void check(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.io.*;
class Disarium{
    private int num;
    private int size;
    public Disarium(int n){
        num = n;
        size = 0;
    }
    void countDigit(){
        for(int i = num; i != 0; i /= 10)
            size++;
    }
    public int sumOfDigits(int n, int p){
        if(n < 10)
            return (int)Math.pow(n, p);
        else{
            int t = (int)Math.pow(n % 10, p);
            return t + sumOfDigits(n / 10, --p);
        }
    }
    public void check(){
        if(num == sumOfDigits(num, size))
            System.out.println(num + " is a Disarium Number.");
        else
            System.out.println(num + " is not a Disarium Number.");
    }
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Number: ");
        int n = Integer.parseInt(br.readLine());
        Disarium obj = new Disarium(n);
        obj.countDigit();
        obj.check();
    }
}

Leave a Reply

%d bloggers like this: