
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Determine Happy Numbers Using Recursion in JavaScript
Happy Number
A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. Whereas if during this process any number gets repeated, the cycle will run infinitely and such numbers are called unhappy numbers.
For example − 13 is a happy number because,
1^2 + 3^2 = 10 and, 1^2 + 0^2 = 1
On the other hand, 36 is an unhappy number.
We are required to write a function that uses recursion to determine whether or not a number is a happy number.
So, let’s write this function out. The key to this function is that we will have to keep a record of the numbers that have already appeared, if the same number makes another appearance, we return false else if the squared digits add up to 1, we return true.
We will use an object to keep track of the already appeared number, we could’ve also used set or Map, but a simple object will do it for us as well.
The code for doing so will be −
Example
const squareSumRecursively = (n, res = 0) => { if(n){ return squareSumRecursively(Math.floor(n/10), res+Math.pow((n%10),2)); }; return res; }; const isHappy = (num, map = {}) => { if(num !== 1){ if(map[num]){ return false; } map[num] = 1; return isHappy(squareSumRecursively(num), map); }; return true; } console.log(isHappy(36)); console.log(isHappy(13)); console.log(isHappy(36)); console.log(isHappy(23));
Output
The output in the console will be −
false true false true