mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Create sqrt_x.py
This commit is contained in:
parent
398c10877c
commit
2626cec18a
27
searching/sqrt_x.py
Normal file
27
searching/sqrt_x.py
Normal 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
|
Loading…
x
Reference in New Issue
Block a user