Narcissistic Number in Java

In this section, we will learn what is a narcissistic number and also create Java programs to check if the given number is a narcissistic number or not. The narcissistic number program is frequently asked in Java coding interviews and academics.

Narcissistic Number

A narcissistic number is a number that is the sum of digits, each raised to the power of the number of digits in the given number. In other words, it is m-digit positive numbers equal to the sum of the m-th powers of their digits. It is also known as pluperfect, or Plus Perfect, or Armstrong number. It is an OEIS sequence A005188.

Let's understand the narcissistic number with examples.

Narcissistic Number Examples

Consider the following numbers.

153 = 13 + 53 + 33 = 1 + 125 +27 = 153

8208 = 84 + 24 + 04 + 84 = 4096 + 16 + 0 + 4096 = 8208

4210818 = 47 + 27 + 17 + 07 + 87 + 17 + 87 = 16384 + 128 + 1 + 0 + 2097152 + 1 + 2097152 = 4210818

We see that the total numbers of digits in the given number are the power and the sum of the powers of each digit is the same number that we have considered. Hence, the given numbers are narcissistic numbers

First few narcissistic numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050, 24678051, 88593477, 146511208, 472335975, 534494836, 912985153, 4679307774, 32164049650, 32164049651, 4338281769391370, 3706907995955475988644380, 19008174136254279995012734740, 186709961001538790100634132976990, and 115132219018763992565095597973971522400.

Steps to Find Narcissistic Number

  1. Read or initialize a number N.
  2. Count the number of digits of the given number N and store it in a variable power.
  3. Find the power of each digit and add the result in a variable sum.
  4. Compare the variable sum with the given number N. If both are equal, the given number is a narcissistic number, else not.

Let's implement the above steps in a Java program.

Narcissistic Number Java Program

NarcissisticNumberExample1.java

Output 1:

Enter the number: 93084
The given number 93084 is a narcissistic number.

Output 2:

Enter the number: 57357
The given number 57357 is not a narcissistic number.

Let's find all the narcissistic numbers between a given range 1 to 1000.

NarcissisticNumberExample2.java

Output:

1
2
3
4
5
6
7
8
9
153
370
371
407





Latest Courses