DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
 
ripsup profile image
Richard Orelup

Looking at your solution it actually fails later in the mix. I was pretty sure you couldn't rely on the numbers not adding up to a single digit happy number (which the only other one beyond 1 is 7.)

1111111 is a happy number which will become 7 after the first iteration and 7 is a happy number. This fails your current function. Here is an updated one that would work by testing if these ever hit 4 instead of length of 1.

function isHappy(n) {
    const u = n.toString().split('').reduce(((ac,cv) => ac + Math.pow(cv,2)), 0);
    if (u === 1) return true;
    if (u === 4) return false;
    else return isHappy(u);
}
Collapse
 
nektro profile image
Meghan (she/her)

Hmmm, good catch :D Although the fact you found all the sad numbers end in 4 is even more interesting to me.🤔🤔

Thread Thread
 
ripsup profile image
Richard Orelup

I read the wikipedia article cause I was like "wait if it's not happy wouldn't that go in to an infinite loop?" :)

Thread Thread
 
heikodudzus profile image
Heiko Dudzus

The number 42 is also in that loop, by the way. :)