Open In App

Check if a Given Number is Happy or Not using JavaScript

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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));

Output
true

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));

Output
true

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads