Skip to content

Instantly share code, notes, and snippets.

@kamweru
Created February 15, 2018 12:38
Show Gist options
  • Save kamweru/b60a268276df043776d15961b19c5510 to your computer and use it in GitHub Desktop.
Save kamweru/b60a268276df043776d15961b19c5510 to your computer and use it in GitHub Desktop.
Python implementation of square root without using built in sqrt() function
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)
@kamweru
Copy link
Author

kamweru commented Feb 15, 2018

Example of how it is done manually

There is no implementation for dealing with numbers that contain zeros.

screenshot_20180215_172248

More examples

example1
example2
example3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment