JS Basic
JS Interview Programs
- JS Interview Programs
- JS Abundant Number
- JS Amicable Number
- JS Armstrong Number
- JS Average of N Numbers
- JS Automorphic Number
- JS Biggest of three numbers
- JS Binary to Decimal
- JS Common Divisors
- JS Composite Number
- JS Condense a Number
- JS Cube Number
- JS Decimal to Binary
- JS Decimal to Octal
- JS Disarium Number
- JS Even Number
- JS Evil Number
- JS Factorial of a Number
- JS Fibonacci Series
- JS GCD
- JS Happy Number
- JS Harshad Number
- JS LCM
- JS Leap Year
- JS Magic Number
- JS Matrix Addition
- JS Matrix Division
- JS Matrix Multiplication
- JS Matrix Subtraction
- JS Matrix Transpose
- JS Maximum Value of an Array
- JS Minimum Value of an Array
- JS Multiplication Table
- JS Natural Number
- JS Number Combination
- JS Odd Number
- JS Palindrome Number
- JS Pascalβs Triangle
- JS Perfect Number
- JS Perfect Square
- JS Power of 2
- JS Power of 3
- JS Pronic Number
- JS Prime Factor
- JS Prime Number
- JS Smith Number
- JS Strong Number
- JS Sum of Array
- JS Sum of Digits
- JS Swap Two Numbers
- JS Triangular Number
JavaScript Program to Check Happy Number
Photo Credit to CodeToFun
π Introduction
In the domain of programming, certain mathematical properties and patterns are often explored. One such interesting concept is the notion of "happy numbers."
In this tutorial, we'll delve into a JavaScript program designed to check whether a given number is a happy number.
π Example
Let's take a look at the JavaScript code that checks whether a given number is a happy number or not.
// Function to calculate the sum of squares of digits
function sumOfSquares(n) {
let sum = 0;
while (n > 0) {
const digit = n % 10;
sum += digit * digit;
n = Math.floor(n / 10);
}
return sum;
}
// Function to check if a number is a happy number
function isHappyNumber(n) {
let slow = n,
fast = n;
do {
slow = sumOfSquares(slow);
fast = sumOfSquares(sumOfSquares(fast));
} while (slow !== fast);
return slow === 1;
}
// Driver program
// Replace this value with your desired number
const number = 19;
// Check if the number is a happy number
if (isHappyNumber(number)) {
console.log(`${number} is a Happy Number.`);
} else {
console.log(`${number} is not a Happy Number.`);
}
π» Testing the Program
To test the program with a different number, replace the value of number in the code.
19 is a Happy Number.
Run the script to check if the number is a happy number.
π§ How the Program Works
- The program defines a function sumOfSquares to calculate the sum of the squares of digits of a given number.
- It then defines a function isHappyNumber that checks whether a given number is a happy number using Floyd's cycle detection algorithm.
- The driver program tests the functionality with a sample number (in this case, 19).
π Between the Given Range
Let's take a look at the javascript code that checks for Happy Numbers in the specified range.
// Function to check if a number is happy
function isHappyNumber(num) {
let seen = new Set();
while (num !== 1 && !seen.has(num)) {
seen.add(num);
num = num.toString().split('').reduce((sum, digit) => sum + digit ** 2, 0);
}
return num === 1;
}
// Function to find happy numbers in a range
function findHappyNumbersInRange(start, end) {
let happyNumbers = [];
for (let i = start; i <= end; i++) {
if (isHappyNumber(i)) {
happyNumbers.push(i);
}
}
return happyNumbers;
}
// Driver program
// Set the range from 1 to 50
const startRange = 1;
const endRange = 50;
// Find happy numbers in the specified range
const happyNumbersInRange = findHappyNumbersInRange(startRange, endRange);
// Output the happy numbers
console.log(`Happy numbers in the range ${startRange} to ${endRange}:\n ${happyNumbersInRange.join(' ')}`);
π» Testing the Program
The program is set to check for happy numbers in the range from 1 to 50. To customize the range, modify the values of startRange and endRange in the code.
Happy numbers in the range 1 to 50: 1 7 10 13 19 23 28 31 32 44 49
Run the script to see the happy numbers in the specified range.
π§ How the Program Works
- The program defines a function isHappyNumber that checks if a given number is a happy number.
- Inside the function, it uses a set (seen) to keep track of numbers encountered during the iterative process.
- It iteratively replaces the number by the sum of the squares of its digits until it becomes 1 or enters a cycle.
- The findHappyNumbersInRange function finds and returns an array of happy numbers in a specified range.
- The main section sets the range from 1 to 50, finds the happy numbers, and outputs the result.
π§ Understanding the Concept of Happy Number
A happy number is a positive integer defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle that does not include 1.
For example, let's take the number 19:
- 12+92 = 82
- 82+22 = 68
- 62+82 = 100
- 12+02+02 = 1
In this case, 19 is a happy number because the process ends with 1.
π’ Optimizing the Program
While the provided program is effective, there are various ways to optimize and enhance it further. Consider exploring different algorithms or incorporating additional features based on your specific requirements.
Feel free to incorporate and modify this code as needed for your specific use case. Happy coding!
π¨βπ» Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (JavaScript Program to Check Happy Number), please comment here. I will help you immediately.