Below is code for long division based finding square root.
But, it fails for decimals, as well as non-square integers.
I mean it gives the same result for 1225, and 1235, i.e. 35.
But, it fails for decimals, as well as non-square integers.
I mean it gives the same result for 1225, and 1235, i.e. 35.
INFINITY_ = 9999999 def sqrtByLongDivision(n,l): i = 0 udigit, j = 0, 0 # Loop counters cur_divisor = 0 quotient_units_digit = 0 cur_quotient = 0 cur_dividend = 0 cur_remainder = INFINITY_ #print 'length of input:', len(n) a = [0]*l # Dividing the number into segments while (n > 0): a[i] = int( n % 100) n = int(n // 100) i += 1 # Last index of the array of segments i -= 1 for j in range(i, -1, -1): cur_remainder = INFINITY_ cur_dividend = cur_dividend * 100 + a[j] for udigit in range(10): if (cur_dividend - (cur_divisor * 10 + udigit) * udigit >= 0): #if ( (cur_remainder >(cur_dividend - ((cur_divisor * 10 + udigit) * udigit))) and (cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0)): # Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit)* udigit) # Updating the units digit of the quotient quotient_units_digit = udigit if cur_remainder == 0: print 'Exiting: cur_remainder ==0' break print ('New rem. :', cur_remainder) else: print(' else break') break # Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit # New divisor is two times quotient cur_divisor = cur_quotient * 2 # Including the remainder in new dividend cur_dividend = cur_remainder return cur_quotient # Driver code x = 1235.789 # Find length of integer y=x length =0 while (y > 0): y //=100 length+= 1 print 'length :', length print(sqrtByLongDivision(x, length))Also, hope once can find the square root for non-square integers, can also find for decimals.