Last active
January 23, 2024 07:01
-
-
Save EDDYMENS/41ec93888ebabc2ea55e47c48aa686fc to your computer and use it in GitHub Desktop.
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
from decimal import Decimal | |
def find_square_root(number, decimal_places, current_result=None, current_decimal_place=1): | |
# Find the integer part of the square root | |
if current_result is None: | |
current_result = int(number / 2) | |
# Check if we have computed the required number of decimal places | |
if current_decimal_place-1 == decimal_places: | |
return current_result | |
# Try placing 0-9 in decimal positions to find the closest square | |
for possible_decimal in range(9, -1, -1): | |
candidate = current_result + Decimal(f'0.{str(possible_decimal).zfill(current_decimal_place)}') | |
squared_result = candidate * candidate | |
if squared_result <= number: | |
return find_square_root(number, decimal_places, candidate, current_decimal_place + 1) | |
# Example usage | |
decimal_places = 3 | |
number = 2 | |
result = find_square_root(number, decimal_places) | |
print(result) # 1.414 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment