Returns the integer square root of a non-negative integer num. Args: num: A non-negative integer. Returns: The integer square root of num. Raises: ValueError: If num is not an integer or is negative. >>> [integer_square_root(i) for i in range(18)] [0,
(num: int)
| 14 | |
| 15 | |
| 16 | def integer_square_root(num: int) -> int: |
| 17 | """ |
| 18 | Returns the integer square root of a non-negative integer num. |
| 19 | Args: |
| 20 | num: A non-negative integer. |
| 21 | Returns: |
| 22 | The integer square root of num. |
| 23 | Raises: |
| 24 | ValueError: If num is not an integer or is negative. |
| 25 | >>> [integer_square_root(i) for i in range(18)] |
| 26 | [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4] |
| 27 | >>> integer_square_root(625) |
| 28 | 25 |
| 29 | >>> integer_square_root(2_147_483_647) |
| 30 | 46340 |
| 31 | >>> from math import isqrt |
| 32 | >>> all(integer_square_root(i) == isqrt(i) for i in range(20)) |
| 33 | True |
| 34 | >>> integer_square_root(-1) |
| 35 | Traceback (most recent call last): |
| 36 | ... |
| 37 | ValueError: num must be non-negative integer |
| 38 | >>> integer_square_root(1.5) |
| 39 | Traceback (most recent call last): |
| 40 | ... |
| 41 | ValueError: num must be non-negative integer |
| 42 | >>> integer_square_root("0") |
| 43 | Traceback (most recent call last): |
| 44 | ... |
| 45 | ValueError: num must be non-negative integer |
| 46 | """ |
| 47 | if not isinstance(num, int) or num < 0: |
| 48 | raise ValueError("num must be non-negative integer") |
| 49 | |
| 50 | if num < 2: |
| 51 | return num |
| 52 | |
| 53 | left_bound = 0 |
| 54 | right_bound = num // 2 |
| 55 | |
| 56 | while left_bound <= right_bound: |
| 57 | mid = left_bound + (right_bound - left_bound) // 2 |
| 58 | mid_squared = mid * mid |
| 59 | if mid_squared == num: |
| 60 | return mid |
| 61 | |
| 62 | if mid_squared < num: |
| 63 | left_bound = mid + 1 |
| 64 | else: |
| 65 | right_bound = mid - 1 |
| 66 | |
| 67 | return right_bound |
| 68 | |
| 69 | |
| 70 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected