JavaScript Program to Find Neon Number in a Range
Last Updated :
08 Mar, 2024
A Neon number is a number where the sum of digits of the square of the number is equal to the number itself. For example, 9 is a Neon number because 9^2 = 81 and the sum of digits of 81 is 8 + 1 = 9, which is the number itself. We want to find all the Neon numbers within a given range.
Below are the approaches to find Neon Numbers in a Range:
Neon Number in a Range Using Iteration
In this approach, we iterate through each number in the given range and check if it’s a Neon number by calculating the sum of digits of the square of the number.
Example: The below code example Uses the simple iteration Method to find a Neon number in a Range in JavaScript.
Javascript
function isNeon(number) {
let square = number * number;
let sum = 0;
while (square > 0) {
sum += square % 10;
square = Math.floor(square / 10);
}
return sum === number;
}
function findNeonNumbersInRange(start, end) {
let neonNumbers = [];
for (let i = start; i <= end; i++) {
if (isNeon(i)) {
neonNumbers.push(i);
}
}
return neonNumbers;
}
console.log(findNeonNumbersInRange(1, 100));
|
Neon Number in a Range Using recursion
In this approach, the function will calculate the square of the number and then sum its digits. If the sum equals the original number, it’s a Neon number. Then, we’ll recursively call the function for the next number in the range until we reach the end.
Example: The below code example Uses the recursion Method to find a Neon number in a Range in JavaScript.
Javascript
function sumOfDigits(number) {
if (number === 0) {
return 0;
}
return (number % 10)
+ sumOfDigits(Math.floor(number / 10));
}
function isNeon(number) {
let square = number * number;
let sum = sumOfDigits(square);
return sum === number;
}
function findNeonInRangeRecursive(start, end, result = []) {
if (start > end) {
return result;
}
if (isNeon(start)) {
result.push(start);
}
return findNeonInRangeRecursive(start + 1, end, result);
}
console.log(findNeonInRangeRecursive(1, 100));
|
Neon Number in a Range Using JavaScript built-in methods
It generates an array of numbers within the given range using Array.from(), filters out the Neon numbers using the filter() method, and returns the resulting array.
Example: The below code example Uses the Array.from(), reduce() and filter() Method to find a Neon number in a Range in JavaScript.
Javascript
function sumOfDigits(number) {
return number
.toString()
.split( "" )
.reduce((acc, digit) => acc + parseInt(digit), 0);
}
function isNeon(number) {
return sumOfDigits(number * number) === number;
}
function findNeonInRange(start, end) {
return Array
.from
(
{ length: end - start + 1 },
(_, index) => index + start,
).filter((num) => isNeon(num));
}
console.log(findNeonInRange(1, 100));
|
Share your thoughts in the comments
Please Login to comment...