-
Notifications
You must be signed in to change notification settings - Fork 0
/
binsqrt.py
38 lines (36 loc) · 1009 Bytes
/
binsqrt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import sys
sys.setrecursionlimit(5000)
def binsqrt(low, high, n, power):
if high >= low:
mid = (high + low) // 2
if mid ** power == n:
return mid
elif mid ** power > n:
return binsqrt(low, mid - 1, n, power)
else:
return binsqrt(mid + 1, high, n, power)
else:
return -1
#inaccurate mode
def flrsqrt(low, high, n, power):
if high >= low:
mid = (high + low) // 2
if mid ** power == n:
return mid
elif mid ** power > n:
return flrsqrt(low, mid - 1, n, power)
else:
return flrsqrt(mid + 1, high, n, power)
else:
return high
def ceilsqrt(low, high, n, power):
if high >= low:
mid = (high + low) // 2
if mid ** power == n:
return mid
elif mid ** power > n:
return ceilsqrt(low, mid - 1, n, power)
else:
return ceilsqrt(mid + 1, high, n, power)
else:
return low