Skip to content

Instantly share code, notes, and snippets.

@Justaus3r
Created August 1, 2023 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Justaus3r/ec40f5e76b4c5265b9ed65ef3e55d813 to your computer and use it in GitHub Desktop.
Save Justaus3r/ec40f5e76b4c5265b9ed65ef3e55d813 to your computer and use it in GitHub Desktop.
A lesson on how not to code
from typing import Union, List, Tuple
# da stupidest and ugliest (with added bonus of bugs) way to calculate square root on a computer. i.e: by human division method
# Working?
# works by splitting the number into pairs , then the first pair
# is divided by a perfect square. the reminder is attached to next pair
# and the divisor is doubled and a constant is determined and attached to
# the divisor and the new divisor is multiplied by the same constant.
# we add the constant to the divisor in next iteration and we keep
# going till the reminder is 0.
def long_div_square_root(n: int) -> Union[int, float]:
def perfect_square(no: int) -> int:
no = no + 1 if no == 1 else no
for n in range(no-1, 0, -1):
if n*n <= no:
return n, n*n
def unknown_const(p_digits: str, divident: int) -> Tuple[int, int, int]:
for u_const_comp in range(9,0, -1):
if (almost_u_const := int(p_digits + str(u_const_comp)) * u_const_comp) <= divident:
return almost_u_const//u_const_comp, u_const_comp, almost_u_const
n_len_even: int = (not len(str(n))%2)
n_pair: List[int] = []
idx: int = 0 if n_len_even else 1
str_n: str = str(n)
square_root: str = ''
for d in str_n:
try:
_ = str_n[idx+1]
n_pair.append(str_n[idx:idx+2])
except IndexError:
break
else:
idx += 2
if not n_len_even:
n_pair = [str_n[0]] + n_pair
n_pair_len: int = len(n_pair)
f_digit: int = int(n_pair.pop(0))
quotient, reminder = perfect_square(f_digit)
p_square: int = quotient
reminder = f_digit - reminder
square_root += str(quotient)
if reminder == 0 and len(n_pair) == 0:
return square_root
p_square *= 2
u_const = 0
sec_pair = n_pair.pop(0)
n_pair.insert(0, str(reminder) + sec_pair)
l_idx = 0
while l_idx < len(n_pair) or reminder != 0:
pair: str = ''
try:
pair = n_pair[l_idx]
except IndexError:
pass
try:
u_const, u_const_comp, smaller_than_pair = unknown_const(str(p_square), int(pair))
except TypeError:
raise Exception("Sowwy. I broke..")
square_root += str(u_const_comp)
p_square = int(str(p_square) + str(u_const_comp)) + u_const_comp
reminder = int(pair) - smaller_than_pair
if reminder == 0:
return square_root
_ = n_pair.pop(0)
try:
f_digit = n_pair.pop(0)
except IndexError:
raise Exception("Something went wrong!, is this number a perfect square?")
else:
n_pair.insert(0, str(reminder) + f_digit)
if len(n_pair) > 1:
l_idx += 1
else:
l_idx = 0
d = long_div_square_root(8281)
print(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment