From 2626cec18a434d5427e5c822aaffeeb003158088 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptography@users.noreply.github.com> Date: Mon, 31 Jul 2023 15:10:15 -0700 Subject: [PATCH] Create sqrt_x.py --- searching/sqrt_x.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 searching/sqrt_x.py diff --git a/searching/sqrt_x.py b/searching/sqrt_x.py new file mode 100644 index 0000000..2399b28 --- /dev/null +++ b/searching/sqrt_x.py @@ -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