The Happy Number

MediumAcc. 85.9%
+30 XP 12

Chasing Unity

A Happy Number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. If you reach 1, the number is happy. If you loop endlessly in a cycle that does not include 1 (like 4, 16, 37...), it is unhappy.

The Assignment

Your function receives a parameter named num.

  1. Use a loop to repeatedly calculate the sum of squares of digits.
  2. If the current number becomes 1, print "true" and exit.
  3. If the current number becomes 4 (this is a known cycle point for unhappy numbers), print "false" and exit.

01EXAMPLE 1

Inputnum = 19
Outputtrue

Explanation: 1^2 + 9^2 = 82 -> 8^2 + 2^2 = 68 -> 6^2 + 8^2 = 100 -> 1^2 + 0^2 + 0^2 = 1.

Constraints

  • Extract digits mathematically.
  • Detect the cycle at 4.
MathLoopsDigits
JavaScript
Loading...
3 Hidden

Input Arguments

num19

Expected Output

true

Click RUN to test your solution