|
| 1 | +""" |
| 2 | +Integer Square Root Algorithm -- An efficient method to calculate the square root of a |
| 3 | +non-negative integer 'num' rounded down to the nearest integer. It uses a binary search |
| 4 | +approach to find the integer square root without using any built-in exponent functions |
| 5 | +or operators. |
| 6 | +* https://en.wikipedia.org/wiki/Integer_square_root |
| 7 | +* https://docs.python.org/3/library/math.html#math.isqrt |
| 8 | +Note: |
| 9 | + - This algorithm is designed for non-negative integers only. |
| 10 | + - The result is rounded down to the nearest integer. |
| 11 | + - The algorithm has a time complexity of O(log(x)). |
| 12 | + - Original algorithm idea based on binary search. |
| 13 | +""" |
| 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__": |
| 71 | + import doctest |
| 72 | + |
| 73 | + doctest.testmod() |
0 commit comments