DEV Community

Riches
Riches

Posted on

Check Whether a Number is a Narcissistic Number or Not in Javascript?

A number is said to be a narcissistic number, if the addition value of each digit raised to the power of numbers of digits available in the original number is equal to the original number.

For more clarification, if the original number has ā€˜nā€™ number of digits, first we have to calculate the nth power of each digit. Then add those value and check if that calculated value and original number both are same then the original number is called as narcissistic number.

Some examples of narcissistic numbers are: 153, 8208, 4210818, ... etc.

In this algorithm below, we will see how to check if a number is a narcissistic number by using Javascript programming language.

Algorithm
Step-1 - Since the input is a number i want to convert to a string first by using the.toString() method

Step-2 - Calculate the number of digits of the original number by using the .length method

Step-3 - Create A variable that will hold the sum of each of the numbers after raising them to the power of the length.

Step-4 - Initiate a loop to extract the digits and calculate the power value of it. Inside that loop add those calculated power values to the variable created above.

Step-5 - Compare both the calculated value with the original number. If the both are same, then the input number is called a narcissistic number then return true else not return false.

function narcissistic(value) {
    value = value.toString()
    let len = value.length
    let digitSum = 0;
    for(let i = 0; i <value.length; i++){
      let eachNumber = parseInt(value[i]);
      digitSum += Math.pow(eachNumber, len);
      console.log(digitSum)
    }
    return digitSum == value
}
console.log(narcissistic(7));
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
jonrandy profile image
Jon Randy šŸŽ–ļø • Edited
const narcissistic = x=>(c=[...''+x]).reduce((a,b)=>a+b**c.length,0)==x
Enter fullscreen mode Exit fullscreen mode
Collapse
 
richeskelechi profile image
Riches

Your Algorithm is top notch. But I am solving for beginners in javascript. After that we will move to advanced concepts and then we can make use of the higher order functions. I am happy for your contributions.

Collapse
 
algodame profile image
Chiamaka Ojiyi

Awesome post Riches. You can add colors to the code snippet by adding js after the 3 opening backticks. Well done.

Collapse
 
richeskelechi profile image
Riches

Thank you

Collapse
 
richeskelechi profile image
Riches

Feel Free To Drop Comments If You Have Any.