Open In App

JavaScript Program to Check whether the Input Number is a Neon Number

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A neon number is a number where the sum of digits of its square equals the number itself. For example, 9 is a neon number because 9^2 = 81, and the sum of the digits 81 is 9. There are several ways to check if a given number is a neon number in JavaScript or not which are as follows:

Using naive method

The most straightforward way to check if a number is a neon number is to square the number, calculate the sum of the digits of the square, and then compare the sum to the original number.

Example: To check whether a number is neon or not using a naive approach.

Javascript




function isNeonNumber(num) {
  let square = num * num;
  let sumOfDigits = 0;
 
  while (square > 0) {
    sumOfDigits += square % 10;
    square = Math.floor(square / 10);
  }
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(8));


Output

true
false

Using string conversion

Another way to approach this problem is to convert the square of the number to a string and then iterate through the characters of the string to calculate the sum of the digits.

Example: To demonstrate checking the number whether it is one number or not by converting it into a string and iterating over it.

Javascript




function isNeonNumber(num) {
  let square = (num * num).toString();
  let sumOfDigits = 0;
 
  for (let digit of square) {
    sumOfDigits += parseInt(digit, 10);
  }
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(8));


Output

true
false

Using array methods

We can also use JavaScript array methods to make the code more concise. In this approach, we convert the square of the number to a string, split the string into an array of characters, and then use the reduce method to calculate the sum of the digits.

Example: To demonstrate checking whether the numbers are neon numbers or not using array methods.

Javascript




function isNeonNumber(num) {
  let sumOfDigits = (num * num)
    .toString()
    .split("")
    .reduce((sum, digit) => {
      return sum + parseInt(digit, 10);
    }, 0);
 
  return sumOfDigits === num;
}
 
console.log(isNeonNumber(9));
console.log(isNeonNumber(5));


Output

true
false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads