// A happy number is a number that eventually reaches 1
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1
// 19 = happy numbe
// Compute the sum of squares of digits of n
function sumOfDigitSquares(n) {
let sum = 0;
while (n > 0) {
const d = n % 10;
sum += d * d;
n = Math.floor(n / 10);
}
return sum;
}
// Determine whether n is a happy number
function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = sumOfDigitSquares(n);
}
return n === 1;
}
function main() {
let a = 1, b = 100;
if (a > b) {
[a, b] = [b, a]; // swap
}
const happyNumbers = [];
for (let i = a; i <= b; i++) {
if (isHappy(i)) {
happyNumbers.push(i);
}
}
console.log(`Happy numbers in range [${a}, ${b}]:`);
console.log(happyNumbers.join(" "));
}
main();
/*
run:
Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
*/