You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
"""
2
15
slow=n
3
16
fast=squared_digits_sum(n)
4
17
5
-
whilefast!=sloworn!=1:
18
+
whilefast!=slow:
6
19
slow=squared_digits_sum(slow)
7
20
fast=squared_digits_sum(squared_digits_sum(fast))
8
21
9
-
iffast==slow:
10
-
returnFalse
11
-
returnTrue
12
-
22
+
returnslow==1
23
+
13
24
defsquared_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
+
"""
14
34
digits_sum=0
15
35
whilen>0:
16
-
n, digit=divmod(n,10)
36
+
n, digit=divmod(n,10)
17
37
digits_squared=digit*digit
18
38
digits_sum+=digits_squared
19
-
returndigits_sum
39
+
returndigits_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