Created
February 15, 2018 12:38
-
-
Save kamweru/b60a268276df043776d15961b19c5510 to your computer and use it in GitHub Desktop.
Python implementation of square root without using built in sqrt() function
This file contains hidden or 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
num = 17956 | |
numlength = len(str(abs(num))) | |
ans = '' | |
rem = 0 | |
def getlast(list): | |
if list: | |
return list[-1] | |
def perfectsquare(num): | |
global rem | |
global ans | |
xlist = [] | |
xsquaredlist = [] | |
for x in range(1,10): | |
xsquared = x * x | |
if xsquared <= num: | |
xlist.append(x) | |
xsquaredlist.append(xsquared) | |
rem = (int(num) % getlast(xsquaredlist)) | |
ans += str(getlast(xlist)) | |
def getdigit(numbers): | |
global num | |
numstring = str(num) | |
numberslist = numbers.split(',') | |
return int(numstring[int(numberslist[0]) : int(numberslist[1])]) | |
def tempcalc(tempans, tempnum): | |
global ans | |
global rem | |
currprods = [] | |
xvalues = [] | |
for x in range(1,10): | |
tempoperand = str(int(tempans)*2) + str(x) | |
currprod = int(tempoperand) * x | |
if currprod <= int(tempnum): | |
currprods.append(currprod) | |
xvalues.append(x) | |
rem = int(tempnum) % getlast(currprods) | |
ans += str(getlast(xvalues)) | |
dig = '' | |
for x in range(0,numlength): | |
key = numlength - x | |
if numlength % 2 == 0: | |
if key % 2 == 0: | |
dig += '-' + str(key) | |
else: | |
if key == 1: | |
dig += ',' + str(numlength) | |
else: | |
dig += ',-' + str(key-1) | |
if len(dig) == 4 or len(dig) == 5: | |
if '-' + str(numlength) in dig: | |
perfectsquare(getdigit(dig)) | |
else: | |
tempnum = str(rem) + str(getdigit(dig)) | |
tempcalc(ans, tempnum) | |
dig = '' | |
else: | |
if key % 2 == 0: | |
dig = '' | |
dig += '-' + str(key) | |
else: | |
if key == numlength: | |
dig += '-' + str(key) | |
dig += ',-' + str(key - 1) | |
else: | |
if key == 1: | |
dig += ',' + str(numlength) | |
else: | |
dig += ',-' + str(key - 1) | |
if len(dig) == 4 or len(dig) == 5: | |
if '-' + str(numlength) in dig: | |
perfectsquare(getdigit(dig)) | |
else: | |
tempnum = str(rem) + str(getdigit(dig)) | |
tempcalc(ans, tempnum) | |
dig = '' | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of how it is done manually
There is no implementation for dealing with numbers that contain zeros.
More examples