icse-promo

Question

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:

Classname:Disarium

Data members/ instance variables:
int num:stores the number
int size:stores the size of the number

Methods/Member functions:
Disarium(int nn):parameterized constructor to initialize the data members num=nn 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 digits of the number(n) to the power of their respective positions(p) using recursive technique
voidcheck():checks whether the number is a disariuim number and displays the result with an appropriate message

Specify the class Disarium giving the 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.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class Disarium
{
    int num,size;

    Disarium(int nn)
    {
        num=nn;
        size=0;	
    }

    void countDigits()
    {
        int temp=num;
        while(temp>0)
        {
            temp=temp/10;
            size++;	
        }
    }

    int sumofDigits(int n,int p)
    {
        if(n==0)
        {
            return 0;
        }
        else
        {
            return (int)Math.pow((n%10),p) +sumofDigits((n/10),(p-1));
        }
    }

    void check()
    {
        if(sumofDigits(num,size)==num)
        {
            System.out.println(num+" is a Disarium number");
        }
        else
        {
            System.out.println(num+" is not a Disarium number");
        }
    }

    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Input a Number");
        int number=sc.nextInt();
        Disarium ob1=new Disarium(number);
        ob1.countDigits();
        ob1.check();
    }
}





				
			

Coding Store

Leave a Reply

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