![]() |
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 Below are the approaches to check if a given number is Happy or not using Javascript: Table of Content Using JavaScript SetIn 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.
Output true Using Floyd’s Cycle Detection AlgorithmFloyd’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.
Output true Using Recursion and MemoizationAnother 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.
Output 19 is a happy number: true |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |