|
| 1 | +def happy_number(n: int) -> bool: |
| 2 | + """ |
| 3 | + Determine if a number is a happy number. |
| 4 | +
|
| 5 | + A happy number is defined as a number which eventually reaches 1 when replaced by the sum of the square of each digit. |
| 6 | + If it loops endlessly in a cycle that does not include 1, it is not a happy number. |
| 7 | +
|
| 8 | + Parameters: |
| 9 | + n (int): The number to be checked. |
| 10 | +
|
| 11 | + Returns: |
| 12 | + bool: True if the number is a happy number, False otherwise. |
| 13 | +
|
| 14 | + """ |
| 15 | + slow = n |
| 16 | + fast = squared_digits_sum(n) |
| 17 | + |
| 18 | + while fast != slow: |
| 19 | + slow = squared_digits_sum(slow) |
| 20 | + fast = squared_digits_sum(squared_digits_sum(fast)) |
| 21 | + |
| 22 | + return slow == 1 |
| 23 | + |
| 24 | +def squared_digits_sum(n: int) -> int: |
| 25 | + """ |
| 26 | + Calculate the sum of the squares of the digits of a number. |
| 27 | +
|
| 28 | + Parameters: |
| 29 | + n (int): The number whose digits are to be squared and summed. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + int: The sum of the squares of the digits of the number. |
| 33 | + """ |
| 34 | + digits_sum = 0 |
| 35 | + while n > 0: |
| 36 | + n, digit = divmod(n, 10) |
| 37 | + digits_squared = digit * digit |
| 38 | + digits_sum += digits_squared |
| 39 | + return digits_sum |
| 40 | + |
| 41 | +# Approach and Reasoning: |
| 42 | +# ----------------------- |
| 43 | +# - The function uses Floyd's Cycle Detection Algorithm (also known as the tortoise and hare algorithm) to detect cycles. Also known as fast and slow pointers. |
| 44 | +# - Two pointers, `slow` and `fast`, are used to traverse the sequence of numbers generated by repeatedly replacing the number with the sum of the squares of its digits. |
| 45 | +# - `slow` moves one step at a time (computes the sum of squares once), while `fast` moves two steps at a time (computes the sum of squares twice). |
| 46 | +# - If there is a cycle (i.e., the number is not happy), `slow` and `fast` will eventually meet at the same number. |
| 47 | +# - If the number is happy, the sequence will eventually reach 1, and the loop will terminate. |
| 48 | + |
| 49 | +# Time Complexity: |
| 50 | +# ---------------- |
| 51 | +# - The time complexity is O(log n), where n is the input number. |
| 52 | +# - The time complexity is O(log_{10}(n)), where n is the input number. This complexity arises from the `squared_digits_sum` function, |
| 53 | +# as the number of digits in n is proportional to log_{10}(n), and each digit is processed in constant time. |
| 54 | + |
| 55 | +# Space Complexity: |
| 56 | +# ----------------- |
| 57 | +# - The space complexity is O(1) because only a constant amount of extra space is used for variables and function calls. |
0 commit comments