|
| 1 | +INFINITY_ = 99999999 |
| 2 | + |
| 3 | +def sqrtByLongDivision(n, decimal_places=5): |
| 4 | + if n < 0: |
| 5 | + raise ValueError("Cannot compute square root of negative numbers.") |
| 6 | + |
| 7 | + # Preparing for long division |
| 8 | + i = 0 |
| 9 | + a = [] |
| 10 | + |
| 11 | + # Dividing the number into segments of two digits |
| 12 | + while n > 0: |
| 13 | + a.append(n % 100) # Extracting two digits (a segment) |
| 14 | + n //= 100 # Moving to the next two digits |
| 15 | + i += 1 |
| 16 | + |
| 17 | + a.reverse() # Reverse to start from the most significant segment |
| 18 | + |
| 19 | + cur_quotient = 0.0 |
| 20 | + cur_divisor = 0.0 |
| 21 | + cur_dividend = 0.0 |
| 22 | + cur_remainder = 0.0 |
| 23 | + |
| 24 | + # Start long division from the first segment |
| 25 | + for j in range(i): |
| 26 | + # Include the next segment in the current dividend |
| 27 | + cur_dividend = cur_dividend * 100 + a[j] |
| 28 | + cur_remainder = INFINITY_ |
| 29 | + |
| 30 | + # Loop to find the largest udigit |
| 31 | + for udigit in range(10): |
| 32 | + # Check if the current divisor and udigit fit |
| 33 | + if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) and |
| 34 | + cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0): |
| 35 | + cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit) |
| 36 | + quotient_units_digit = udigit |
| 37 | + |
| 38 | + # Update the quotient and divisor |
| 39 | + cur_quotient = cur_quotient * 10 + quotient_units_digit |
| 40 | + cur_divisor = cur_quotient * 2 |
| 41 | + cur_dividend = cur_remainder |
| 42 | + |
| 43 | + # Calculate decimal places |
| 44 | + for _ in range(decimal_places): |
| 45 | + cur_dividend *= 100 # Shift the remainder for decimal place calculation |
| 46 | + cur_remainder = INFINITY_ |
| 47 | + |
| 48 | + for udigit in range(10): |
| 49 | + if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) and |
| 50 | + cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0): |
| 51 | + cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit) |
| 52 | + quotient_units_digit = udigit |
| 53 | + |
| 54 | + cur_quotient = cur_quotient * 10 + quotient_units_digit |
| 55 | + cur_divisor = cur_quotient * 2 |
| 56 | + cur_dividend = cur_remainder |
| 57 | + |
| 58 | + # Return the square root as a float |
| 59 | + return cur_quotient / (10 ** decimal_places) |
| 60 | + |
| 61 | +# Driver code |
| 62 | +x = int(input("Enter the Number: ")) |
| 63 | +print(sqrtByLongDivision(x)) # Output: square root of 11 as float |
| 64 | + |
| 65 | + |
0 commit comments