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);
}
I'm a fan of Open Source and have a growing interest in serverless and edge computing. I'm not a big fan of spiders, but they're doing good work eating bugs. I also stream on Twitch.
e: updated to work with all happy numbers
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.
Hmmm, good catch :D Although the fact you found all the sad numbers end in 4 is even more interesting to me.🤔🤔
I read the wikipedia article cause I was like "wait if it's not happy wouldn't that go in to an infinite loop?" :)
The number 42 is also in that loop, by the way. :)
Your code in ES2016+ (and a bit less readable):
You could even shorten the
toString
by replacing it with a template string which will do an implicittoString
.