- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Determining happy numbers using recursion 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
- Related Articles
- Determining whether numbers form additive sequence in JavaScript
- Happy Numbers in Python
- C++ Program to Find Fibonacci Numbers using Recursion
- Determining isomorphic strings JavaScript
- Finding smallest number using recursion in JavaScript
- Fetching object keys using recursion in JavaScript
- Recursion example in JavaScript to display numbers is descending order?
- Array flattening using loops and recursion in JavaScript
- Decimal to binary conversion using recursion in JavaScript
- C++ program to Find Sum of Natural Numbers using Recursion
- Java Program to Find Sum of N Numbers Using Recursion
- Determining rightness of a triangle – JavaScript
- Determining full house in poker - JavaScript
- Determining a pangram string in JavaScript
- Determining beautiful number string in JavaScript
