Thursday 26 March 2015

PROGRAM 8 : ENTER A NUMBER TO CHECK WHETHER IT IS A DISARIUM NUMBER OR NOT.

( Disarium number is a number which is equal to the total sum of its digits raised to their position in the number.)

Example : 135 is a DISARIUM NUMBER .

SUM = 1^1 + 3^2 + 5^3(position of '1' is first ; of '3' is second and '5' is third)
         = 1 + 9 + 125   ( '^' is to express the number "raised to" some other number)
         = 135 , i.e the number itself 


PROGRAM:

import java.io.*;
public class disarium_number
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a number to find out whether it is a disarium number or not:");
        int num = Integer.parseInt(br.readLine());
        int copy = num , d , sum = 0;
        String str = Integer.toString(num); // CONVERTING INTEGER TO STRING
        int len = str.length(); // FINDING LENGTH OF THE STRING
        while(len>0){
            d = copy%10; // EXTRACTING LAST DIGIT OF THE NUMBER
            sum += (int)Math.pow(d , len); // ADDING THE NUMBER RAISED TO ITS EXPONENT THAT IS THE 'len'
            len--; // reducing len by '1'
            copy = copy/10; // dividing the number by '10'
        }
        if(sum==num) // checking whether total sum of the raised numbers is equal to the number itself
           System.out.println("The number is a disarium number.");
        else
           System.out.println("The number is not a disarium number.");
        }
    }

No comments:

Post a Comment