Welcome to my personal website. I use this space to share some of my thoughts and software that I write in my free time. Sometimes I also publish photos. If you want to get in touch please use LinkedIn or Mastodon.
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
For example, the number 19 is divided into 1^2 and 9^2, then added together as 82, then divided again, etc. After some iterations this reaches 100 which is 1^2 + 0^2 + 0^2 = 1. On the other hand, 2 keeps ever incremententing.
The programming aspect is relatively easy to solve in Python when converting the types to a string and then converting the string to a list.
When solving this problem I recommend to first focus on the loop that eventually reaches to 100 and implement the valid case. Once this is done, one can print out the numbers that get visited when using the same algorithm with 2. It becomes obvious that the chain of visited numbers looks something like this: 2 -> 4 -> ... -> 4.
With this observation we know that invalid numbers have loops and we can use a set to detect if we encounter a loop.
Runtime: 71 ms, faster than 14.54% of Python3 online submissions for Happy Number.
Memory Usage: 13.9 MB, less than 14.75% of Python3 online submissions for Happy Number.
About the author
Friedrich Ewald is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.