Happy number
Easy TimeO(log n) SpaceO(log n)
Replace a number by the sum of the squares of its digits, and repeat. Some numbers reach 1 and stay there, because 1 maps to itself; every other number falls into a cycle that never contains 1. Given a positive integer n, return true when the repetition starting at n reaches 1 and false when it does not.
Examples
Example 1
- Input
- n = 19
- Output
true1² + 9² = 82, then 68, then 100, then1² + 0² + 0² = 1.
Example 2
- Input
- n = 4
- Output
- 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, back where it started.
false
The Code
function digitSquareSum(n) {
let total = 0;
while (n > 0) {
const d = n % 10;
total += d * d;
n = Math.floor(n / 10);
}
return total;
}
function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = digitSquareSum(n);
}
return n === 1;
}
isHappy(19);Done
More like this
All math & numbers examples (8) →- Prime check Only test odd divisors, and only up to the square root.
- Prime sieve Cross out every multiple; whatever survives is prime.
- Roman → integer Subtract when a smaller symbol sits before a bigger one.
- Integer → Roman Greedily take the largest symbol that still fits.
- Collatz Halve it if even, triple-plus-one if odd — always reaches 1.
- Newton’s sqrt Average your guess with n over your guess; it converges fast.