Java Program to Check Narcissistic Decimal Number

In the previous article, we have discussed Java program to Check Kaprekar Number

In this article we are going to understand what Narcisstic Decimal number is and how we can check whether a number is Narcisstic Decimal number or not in Java with examples.

Program to Check Narcissistic Decimal Number

Narcisstic Decimal numbers are non-negative numbers, whose digits when raised to the power of m, m being the number of digits, add up to the number itself.

Example :

  • 5: 51=5 Narcisstic Decimal number
  • 10: 12+02 = 1 Not a Narcisstic Decimal number
  • 153= 13+53+33=153 Narcisstic Decimal number

In the above examples the numbers 5 and 153 are Narcisstic Decimal numbers as their digits when raised to the power of number of digits is equal to the number itself. However 10 is not the Narcisstic Decimal number here.

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Approach :

  1. Enter/declare a number and store it .
  2. We calculate the number of digits in the number and store it in a variable digits.
  3. The number is raised to the power stored in variable digits. Then all of them are added.
  4. If the sum is equal to the entered number, then the number is said to be a Narcisstic Decimal number.

Program:

import java.util.Scanner;

public class NarcissticDecimalNumber
{
    public static void main(String args[])
    {
        //Taking the number as input from the user using scanner class
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = scan.nextInt();

        int sum = 0, temp = num, remainder, digits = numberOfDig(num);
        //Iterates through the digits and adds their raised power to sum
        while(temp>0)
        {
            remainder = temp%10;
            sum = sum + (int)Math.pow(remainder,digits);
            temp = temp/10;
        }

        if(sum==num)
        {
            System.out.println(num+" is a Narcisstic Decimal Number");
        }
        else
        {
            System.out.println(num+" is Not a Narcisstic Decimal Number");
        }
    }

    //Function that returns the number of digits
    static int numberOfDig(int num)
    {
        int digits = 0;
        while (num > 0)
        {
            digits++;
            num = num / 10;
        }
        return digits;
    }
}


Output:

Case-1

Enter a number : 153
153 is a Narcisstic Decimal Number

Case-2

Enter a number : 553
553 is a Narcisstic Decimal Number

Related Java Programs: