JavaScript Narcissistic number

JavascriptWeb DevelopmentObject Oriented Programming

Narcissistic number

A narcissistic number in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits.

For example −

153 = 1^3 + 5^3 + 3^3 = 1+125+27 = 153

Similarly,

1 = 1^1 = 1

Approach

We will first count the number of digits using a while loop. Then with another while loop, we pick last digit of the number and add its (count) th power to a variable sum. After the loop we return a boolean checking whether the sum is equal to the number or not.

The code for this approach will be −

Example

const isNarcissistic = (num) => {
   let m = 1, count = 0;
   while(num / m > 1){
      m *= 10;
      count++;
   };
   let sum = 0, temp = num;
   while(temp){
      sum += Math.pow(temp % 10, count);
      temp = Math.floor(temp / 10);
   };
   return sum === num;
};
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));

Output

The output in the console will be −

true
true
false
false
raja
Published on 24-Aug-2020 09:55:15
Advertisements