Create sqrt_x.py

This commit is contained in:
marina 2023-07-31 15:10:15 -07:00 committed by GitHub
parent 398c10877c
commit 2626cec18a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

27
searching/sqrt_x.py Normal file
View File

@ -0,0 +1,27 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
def sqrt(x) -> int:
if x < 2:
return x
left, right = 2, x // 2
while left <= right:
pivot = left + (right - left) // 2
num = pivot * pivot
if num > x:
right = pivot - 1
elif num < x:
left = pivot + 1
else:
return pivot
return right