DEV Community

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

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

e: updated to work with all 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. :)

Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

Your code in ES2016+ (and a bit less readable):

const isHappy = n => {
  if (n === 4) return false;

  const u = [...n.toString()].reduce((ac, c) => ac + (c ** 2), 0);

  return u === 1 || isHappy(u);
};
Collapse
 
nickytonline profile image
Nick Taylor

You could even shorten the toString by replacing it with a template string which will do an implicit toString.

const isHappy = n => {
  if (n === 4) return false;

  const u = [...`${n}`].reduce((ac, c) => ac + (c ** 2), 0);

  return u === 1 || isHappy(u);
};