Check if a Given Number is Happy or Not using JavaScript
Last Updated :
27 Jun, 2024
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:
Using JavaScript Set
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.
JavaScript
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));
Using Floyd's Cycle Detection Algorithm
Floyd's cycle detection algorithm involves using two pointers: one moving twice as fast as the other. If there's a cycle, the two pointers will eventually meet. In this approach, we'll apply Floyd's algorithm to detect cycles in the sequence of numbers generated during the process.
Example: To demonstrate checking the given number whether it a happy number or not using floyd's cycle detection algorithm.
JavaScript
function getNext(number) {
let sum = 0;
while (number > 0) {
let digit = number % 10;
sum += digit * digit;
number = Math.floor(number / 10);
}
return sum;
}
function isHappy(number) {
let slow = number;
let fast = getNext(number);
while (fast !== 1 && slow !== fast) {
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast === 1;
}
console.log(isHappy(19));
Using Recursion and Memoization
Another approach to determine if a given number is a happy number is to use recursion combined with memoization. Memoization allows us to store the results of previous computations, which can help detect cycles more efficiently and reduce redundant calculations. This approach involves recursively computing the sum of the squares of the digits and using a map to store the intermediate results to detect any cycles.
Example: The following example demonstrates checking if a given number is a happy number using recursion and memoization.
JavaScript
function sumOfSquares(n) {
let sum = 0;
while (n > 0) {
let digit = n % 10;
sum += digit * digit;
n = Math.floor(n / 10);
}
return sum;
}
function isHappyNumber(n, seen = new Map()) {
if (n === 1) {
return true;
}
if (seen.has(n)) {
return false;
}
seen.set(n, true);
const nextNumber = sumOfSquares(n);
return isHappyNumber(nextNumber, seen);
}
const number = 19;
const result = isHappyNumber(number);
console.log(`${number} is a happy number: ${result}`); // Output: 19 is a happy number: true
Output19 is a happy number: true
Similar Reads
Check if a Given String is Binary String or Not in JavaScript Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string.Example:Input: "101010"Output: True, bin
3 min read
How to check a number is even without using modulo operator in JavaScript ? In this article, we learn how to check if a number is even without using the % or modulo operator. The methods are mentioned below. 1. By using the bitwise '&' operator: When & operation is done on a number with 1 it will return 0 if the number is zero. We will use this method to check if th
3 min read
JavaScript Program to Check if a Number is Odd or Even We are going to learn how to check whether the number is even or Odd using JavaScript. In the number system, any natural number that can be expressed in the form of (2n + 1) is called an odd number, and if the number can be expressed in the form of 2n is called an even number.Even = {2k : k â Z}(whe
3 min read
How to check if a number evaluates to Infinity using JavaScript ? The task is to check whether the number evaluates to infinity or not with the help of JavaScript. Here are a few techniques discussed. Approach 1: Checking if the number is equal to the Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY . Example: This example uses the approach discussed above. ht
2 min read
How to Check if a Given Number is Fibonacci Number in JavaScript ? The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. Checking for Fibonacci numbers involves verifying whether a given number appears in this sequence. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and
4 min read
How to check whether a number is NaN or finite in JavaScript ? When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
3 min read