Skip to content

Instantly share code, notes, and snippets.

@dojeda
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dojeda/c35b5d11aa8e99b244e0 to your computer and use it in GitHub Desktop.
Save dojeda/c35b5d11aa8e99b244e0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def sqrt(x):
begin = 0
end = x
while begin <= end:
mid = begin + (end - begin) // 2
if mid*mid == x:
return mid
elif mid*mid < x:
begin = mid + 1
else:
end = mid - 1
return end
def main():
import math
x = 18014398509481983
si = int(math.sqrt(x))
sk = sqrt(x)
## all these assert fail
assert(si**2 == x) # this one fails because sqrt uses floating-point
assert(sk == si) # this one fails because my implementation gives the lowest sqrt
assert(sk**2 == x) # this one fails because x does not have a perfect square root
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment