In [39]:
import math
def squareRoot_n(n, s, e):
#print (n, s, e)
if s == e:
if s*s <= n:
return s
else:
return s-1
elif s > e:
return e
mid = int(s + (e-s) / 2)
sq = mid*mid
if sq == n:
return mid
elif sq > n:
return squareRoot_n(n, s, mid-1)
else:
return squareRoot_n(n, mid+1, e)
def squareRoot(n):
return squareRoot_n(n, 0, n)
In [ ]:
for i in range(1000):
sq = squareRoot(i)
expected = int(math.sqrt(i))
assert sq == expected, "fail {} / true:{}".format(sq,expected)
print ("All tests PASS")
In [ ]: