DEV Community

loading...

Discussion on: The Happy Number Problem

Collapse
khuongduybui profile image
Duy K. Bui

Your solution makes sense, mathematically.
However, I think it's a wasted chance to use and explain recursion with carryover.
The function can be something like this:

function isHappy(n, seenSums = []) {
  // ... same as above
  if (sum === 1) return true; // answer found
  if (seenSums.includes(sum)) return false; // generic infinite loop detection mechanism
  return isHappy(sum, seenSums.concat([sum])); // recursion with carryover
}
Enter fullscreen mode Exit fullscreen mode
Collapse
luispeerez profile image
Luis Perez Bautista

You could use Set instead of an array for seenSums, that way your validation to check the infinite loop could be done in constant time by changing

  if (seenSums.includes(sum)) return false; // generic infinite loop detection mechanism
Enter fullscreen mode Exit fullscreen mode

for

  if (seenSums.has(sum)) return false; // generic infinite loop detection mechanism
Enter fullscreen mode Exit fullscreen mode