Last active
August 29, 2015 14:19
-
-
Save dojeda/c35b5d11aa8e99b244e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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