Test / frac_to_bin.py
Drbrain0620's picture
Upload folder using huggingface_hub
e3af2b1 verified
BASE = 2
def to_binary(a, b):
"""
Converts a fraction (a/b) to a binary representation.
Parameters:
a (int): The numerator of the fraction.
b (int): The denominator of the fraction.
Returns:
tuple: A tuple containing two elements. The first element is the period length,
and the second element is the binary representation of the fraction.
If the fraction is a repeating decimal, the binary representation will
contain 'r' to indicate the repeating part.
"""
temp = a
chk = [a]
ret = ''
while True:
temp *= BASE
if temp > b:
temp -= b
ret += '1'
elif temp == b:
ret += '1'
return (0, '.' + ret)
else:
ret += '0'
chk.append(temp)
if (len(chk) - len(set(chk))) != 0:
for i in range(len(chk) - 1):
if chk[i] == chk[-1]:
ret = ret[:i] + 'r' + ret[i:]
break
return len(ret[ret.index('r'):]) - 1, '.' + ret
nu = int(input('분자: '))
de = int(input('분모: '))
period_length, binary_repr = to_binary(nu, de)
print(f"{nu}/{de}, {(period_length, binary_repr)}")