Recursion: Happy Number

Published by Deep Xavier in

A happy number is a number which yields a 1 by repeatedly summing up the square of its digits. If such a process results in an endless cycle which is 4, then the number is said to be an unhappy number.

Sample computation:

139 = 1^2 + 3^2 + 9^2 = 1 + 9 + 81 = 91
91 = 9^2 + 1^2 = 81 + 1 = 82
82 = 8^2 + 2^2 = 64 + 4 = 68
68 = 6^2 + 8^2 = 36 + 64 = 100
100 = 1^2 + 0^2 + 0^2 = 1 + 0 + 0 = 1

We stopped at 1 (because continuing it will be an endless cycle), thus, 139 is a happy number.

67 = 6^2 + 7^2 = 36 + 49 = 85
85 = 8^2 + 5^2 = 64 + 25 = 89
89 = 8^2 + 9^2 = 64 + 81 = 145
145 = 1^2 + 4^2 + 5^2 = 1 + 16 + 25 = 42
42 = 4^2 + 2^2 = 16 + 4 = 20
20 = 2^2 + 0^2 = 4 + 0 = 4 

We stopped at 4 (because continuing it will be an endless cycle), thus, 67 is an unhappy number.

Create a function that accepts a number and determines whether the number is a happy number or not. Return True if so, False otherwise.

Examples

is_happy(67) ➞ False

is_happy(89) ➞ False

is_happy(139) ➞ True

is_happy(1327) ➞ False

is_happy(2871) ➞ False

is_happy(3970) ➞ True

Notes

  • You are expected to solve this challenge via recursion.
  • You can check on the Resources tab for more details about recursion.
  • A non-recursive version of this challenge can be found in here.
Watch a quick demo on how Edabit works.