11def perfect_cube (n : int ) -> bool :
22 """
33 Check if a number is a perfect cube or not.
4-
4+
55 Note: This method uses floating point arithmetic which may be
66 imprecise for very large numbers.
7-
7+
88 >>> perfect_cube(27)
99 True
1010 >>> perfect_cube(64)
@@ -30,12 +30,12 @@ def perfect_cube(n: int) -> bool:
3030 is_negative = True
3131 else :
3232 is_negative = False
33-
33+
3434 val = n ** (1 / 3 )
3535 # Round to avoid floating point precision issues
3636 rounded_val = round (val )
3737 result = rounded_val * rounded_val * rounded_val == n
38-
38+
3939 # For negative numbers, we need to check if the cube root would be negative
4040 return result and not (is_negative and rounded_val == 0 )
4141
@@ -45,7 +45,7 @@ def perfect_cube_binary_search(n: int) -> bool:
4545 Check if a number is a perfect cube or not using binary search.
4646 Time complexity : O(Log(n))
4747 Space complexity: O(1)
48-
48+
4949 >>> perfect_cube_binary_search(27)
5050 True
5151 >>> perfect_cube_binary_search(64)
@@ -91,29 +91,29 @@ def perfect_cube_binary_search(n: int) -> bool:
9191 """
9292 if not isinstance (n , int ):
9393 raise TypeError ("perfect_cube_binary_search() only accepts integers" )
94-
94+
9595 # Handle zero and negative numbers
9696 if n == 0 :
9797 return True
9898 if n < 0 :
9999 n = - n
100-
100+
101101 # Quick checks to eliminate obvious non-cubes
102102 # Check last three digits using modulo arithmetic
103103 # Only 0, 1, 8, 7, 4, 5, 6, 3, 2, 9 can be cubes mod 10
104104 # But for cubes, the pattern is more complex
105105 last_digit = n % 10
106106 if last_digit not in {0 , 1 , 8 , 7 , 4 , 5 , 6 , 3 , 2 , 9 }:
107107 return False
108-
108+
109109 # More refined check: cubes mod 7 can only be 0, 1, 6
110110 if n % 7 not in {0 , 1 , 6 }:
111111 return False
112-
112+
113113 # More refined check: cubes mod 9 can only be 0, 1, 8
114114 if n % 9 not in {0 , 1 , 8 }:
115115 return False
116-
116+
117117 # Estimate the cube root using logarithms for very large numbers
118118 # This gives us a much better initial right bound
119119 if n > 10 ** 18 :
@@ -126,7 +126,7 @@ def perfect_cube_binary_search(n: int) -> bool:
126126 else :
127127 # For smaller numbers, use the standard approach
128128 left , right = 0 , n // 2 + 1
129-
129+
130130 # Binary search
131131 while left <= right :
132132 mid = (left + right ) // 2
@@ -135,18 +135,19 @@ def perfect_cube_binary_search(n: int) -> bool:
135135 if mid > 10 ** 6 and mid * mid > n // mid :
136136 right = mid - 1
137137 continue
138-
138+
139139 cube = mid * mid * mid
140140 if cube == n :
141141 return True
142142 elif cube < n :
143143 left = mid + 1
144144 else :
145145 right = mid - 1
146-
146+
147147 return False
148148
149149
150150if __name__ == "__main__" :
151151 import doctest
152+
152153 doctest .testmod ()
0 commit comments