Happy numbers in JavaScript
Advanced · 4 min read
Take a number, square each of its digits, and add the squares up. Then do the same to the result, and keep going. For 7 you get 49, then 16 + 81 = 97, then 81 + 49 = 130, then 10, then 1. Once you reach 1 you stay there, and 7 is called a happy number. Some numbers never reach 1. They go round in a loop forever, and those are unhappy.
Happy numbers are a popular interview question because the tricky part is the loop. If you don't plan for numbers that never reach 1, your code never stops. In this tutorial you will write isHappy(n) with a Set that notices when a value repeats, then find where every unhappy number ends up and why the loop is guaranteed to finish. You need to know while loops and the digit tricks % 10 and Math.floor(n / 10).
What a Set is
A Set is a collection that holds each value at most once. You add values with add and ask whether something is in it with has.
const seen = new Set();
seen.add(4);
seen.add(16);
console.log(seen.has(4)); // true
console.log(seen.has(37)); // false
That is all we need from it: a memory of every number the chain has already visited.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
50 Happy numbers
hardRepeatedly replace a number by the sum of the squares of its digits. If it reaches 1 the number is happy; otherwise it falls into a cycle. Prove the loop always ends, and find where the unhappy ones go.
Stuck? Three hints, smallest first
- 1. Track what you have already seen, and stop when a value repeats.
- 2. Every unhappy number reaches the same eight-element cycle.
- 3. For any
nof four digits or more the next value is far smaller, so the sequence cannot run away.
Step 1: one step of the chain
function squareDigits(n) {
let rest = n;
let sum = 0;
while (rest > 0) {
const d = rest % 10;
sum += d * d;
rest = Math.floor(rest / 10);
}
return sum;
}
console.log(squareDigits(7)); // 49
console.log(squareDigits(49)); // 97
console.log(squareDigits(130)); // 10
The loop takes the last digit, adds its square to sum, and drops that digit, until no digits are left.
Step 2: follow a chain
Before writing the test, it helps to look at some chains. This helper records each value, and stops early if it reaches 1:
const chainFrom = (n, steps) => {
const out = [n];
for (let i = 0; i < steps && out.at(-1) !== 1; i++) out.push(squareDigits(out.at(-1)));
return out;
};
console.log(chainFrom(7, 10).join(' > ')); // 7 > 49 > 97 > 130 > 10 > 1
console.log(chainFrom(4, 8).join(' > ')); // 4 > 16 > 37 > 58 > 89 > 145 > 42 > 20 > 4
out.at(-1) is the last item in the array. The chain from 7 reaches 1 in five steps. The chain from 4 never does: after eight steps it is back at 4, and from there it would repeat the same eight numbers forever.
Step 3: the loop that never ends
The first idea most people have is "keep stepping until you reach 1", written as while (n !== 1) n = squareDigits(n);. For 7 that works. For 4 it runs forever, because 4 never reaches 1. Your page or your server would freeze.
So the loop needs a second way out: stop when you see a value you have seen before. A repeat means you are in a cycle, and a cycle that doesn't contain 1 can never reach it.
Step 4: isHappy with a Set
function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = squareDigits(n);
}
return n === 1;
}
console.log(isHappy(7)); // true
console.log(isHappy(4)); // false
The loop keeps going while two things are true: we haven't reached 1, and we haven't been here before. When it stops, there are only two possibilities. Either n is 1, which means happy, or n is a repeat, which means unhappy. The last line returns which one it was.
Step 5: list the happy numbers
const happyBelow50 = [];
for (let n = 1; n < 50; n++) if (isHappy(n)) happyBelow50.push(n);
console.log(happyBelow50.join(', ')); // 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49
let count = 0;
for (let n = 1; n <= 100; n++) if (isHappy(n)) count++;
console.log(count); // 20
20 of the first hundred numbers are happy. Every power of ten is happy straight away: 10, 100 and 1000 all have a single 1 and zeros, so the first step gives 1.
Step 6: why the loop always ends
The Set stops cycles. But could a chain keep climbing to bigger and bigger numbers, never repeating? No, and here is why.
Each digit is at most 9, and 9 squared is 81. So a number with k digits gives at most 81 times k. A four-digit number gives at most 324:
console.log(squareDigits(9999)); // 324
console.log(squareDigits(1000)); // 1
Every number with four or more digits shrinks on the first step. So after a step or two, the chain is stuck below 1000. There are fewer than 1000 values down there, so it must either reach 1 or repeat one of them. Either way, the Set loop stops.
Even better, every unhappy number falls into the same cycle you saw from 4: 4, 16, 37, 58, 89, 145, 42, 20, and back to 4. The answer panel checks this for every unhappy number below 500. Some code uses it as a shortcut, checking n === 4 instead of keeping a Set. It works, but it relies on a fact you have to know in advance. The Set version doesn't.
The full solution
The answer panel has squareDigits, isHappy and chainFrom, lists the happy numbers below 50, counts them to 100, checks that every unhappy number below 500 passes through 4, and checks that every number from 1000 to 1999 shrinks in one step. Press Run to see the output.
function squareDigits(n) {
let rest = n;
let sum = 0;
while (rest > 0) {
const d = rest % 10;
sum += d * d;
rest = Math.floor(rest / 10);
}
return sum;
}
function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = squareDigits(n);
}
return n === 1;
}
const chainFrom = (n, steps) => {
const out = [n];
for (let i = 0; i < steps && out.at(-1) !== 1; i++) out.push(squareDigits(out.at(-1)));
return out;
};
const happyBelow50 = [];
for (let n = 1; n < 50; n++) if (isHappy(n)) happyBelow50.push(n);
const happyToHundred = [];
for (let n = 1; n <= 100; n++) if (isHappy(n)) happyToHundred.push(n);
// Every unhappy number below 500 passes through 4.
let allReachFour = true;
for (let n = 2; n < 500; n++) {
if (isHappy(n)) continue;
const seen = new Set();
let m = n;
let hitFour = false;
while (!seen.has(m)) {
seen.add(m);
m = squareDigits(m);
if (m === 4) hitFour = true;
}
if (!hitFour) allReachFour = false;
}
// Nothing can run away: four digits or more always shrinks.
let alwaysShrinks = true;
for (let n = 1000; n < 2000; n++) if (squareDigits(n) >= n) alwaysShrinks = false;
console.log('7 is happy :', isHappy(7), chainFrom(7, 10));
console.log('4 is not :', isHappy(4), chainFrom(4, 8));
console.log('happy below 50:', happyBelow50);
console.log('how many to 100:', happyToHundred.length);
console.log('squareDigits(9999):', squareDigits(9999), '<- far below 9999');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('7 is happy, and 4 is not', [isHappy(7), isHappy(4)], [true, false]);
test('the chain from 7 reaches 1 in five steps', chainFrom(7, 10), [7, 49, 97, 130, 10, 1]);
test('the chain from 4 comes back to 4 after eight', chainFrom(4, 8), [4, 16, 37, 58, 89, 145, 42, 20, 4]);
test('the happy numbers below 50', happyBelow50, [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]);
test('20 of the first hundred are happy', happyToHundred.length, 20);
test('every power of ten is happy, trivially', [1, 10, 100, 1000].every(isHappy), true);
test('and every unhappy number below 500 passes through 4', allReachFour, true);
test('the loop always ends, because 4 digits or more always shrinks', [alwaysShrinks, squareDigits(9999)], [true, 324]);
test('so nothing above 1000 can escape upwards', squareDigits(1000) < 1000, true);
Termination is the part worth proving rather than assuming. The largest value squareDigits can return for a k-digit input is 81k, which for four digits is 324 — so anything of four digits or more shrinks immediately, and the sequence is trapped below 1000 forever after. A finite region plus a deterministic step means either 1 or a repeat, which is exactly what the Set detects.
The unhappy destination is always the same eight-element cycle, 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. That makes a shortcut possible: instead of remembering every value seen, test for n === 4. It is a real optimisation and a fragile one, because it encodes a fact about base 10 that the Set version does not need to know.
Common mistakes
- Looping until 1 with no other exit. For an unhappy number like 4,
while (n !== 1)never stops. - Checking the Set after adding. If you
add(n)and then askhas(n), the answer is alwaystrue. Check first, then add. - Changing
ninsidesquareDigits. Work on a copy likerest, so the caller's value is never touched.
Try it yourself
- Write
stepsToHappy(n)that returns how many steps a happy number takes to reach 1, or-1for an unhappy one. 7 should give 5. - Replace the
Setwith then === 4shortcut and check that both versions agree for every number up to 1000. - Find the happy number below 1000 with the longest chain.