How to use Set In Javascript
In this approach, we’ll repeatedly square the digits of the number and sum them up until we reach either 1 or encounter a number that has already been seen. We’ll use a set to keep track of the numbers encountered during the process and check if we encounter 1.
Example: To demonstrate checking the given number whether it is a happy number or not using the set data structure.
function isHappy(number) {
let seen = new Set();
while (number !== 1 && !seen.has(number)) {
seen.add(number);
let sum = 0;
while (number > 0) {
let digit = number % 10;
sum += digit * digit;
number = Math.floor(number / 10);
}
number = sum;
}
return number === 1;
}
console.log(isHappy(10));
Output
true
Check if a Given Number is Happy or Not using JavaScript
In mathematics, a happy number is defined as a number that eventually reaches 1 when replaced by the sum of the squares of each digit. If this process results in 1, then the number is considered happy; otherwise, it leads to an endless cycle of numbers.
Example: 19 is a happy number because:
1^2 + 9^2 = 1 + 81 = 82
8^2 + 2^2 = 64 + 4 = 68
6^2 + 8^2 = 36 + 64 = 100
1^2 + 0^2 + 0^2 = 1
Since the process eventually reaches 1, 19 is a happy number.
Below are the approaches to check if a given number is Happy or not using Javascript:
Table of Content
- Using a Set
- Using Floyd’s Cycle Detection Algorithm
Contact Us