Skip to content

Instantly share code, notes, and snippets.

@haile01
Created April 23, 2021 09: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 haile01/bacd667b554804a8e3362e6216aa6cb1 to your computer and use it in GitHub Desktop.
Save haile01/bacd667b554804a8e3362e6216aa6cb1 to your computer and use it in GitHub Desktop.
Fomat result of division of integers into decimal form
#!/usr/bin/env python3
import math
import sys
# Usage: ./main.py a b
# Prints out result of division a/b in format x.y(z)
# Example: 13/12 = 1.08(3)
a, b = [int(c) for c in sys.argv[1:]]
# turn a / b into x.y(z)
def find (x):
res = 9
cnt = 1
while (res % x != 0):
res = 10 * res + 9
cnt += 1
return int(res / x), cnt
x = int(a / b)
remain = a - x * b
# print('x = {0}, remain = {1}'.format(x, remain))
cnt_2 = 0
cnt_5 = 0
temp = 1
temp_b = b
while temp_b % 2 == 0:
temp *= 2
temp_b = int(temp_b / 2)
cnt_2 += 1
while temp_b % 5 == 0:
temp *= 5
temp_b = int(temp_b / 5)
cnt_5 += 1
while remain % 2 == 0 and cnt_2 > 0:
remain = int(remain / 2)
temp = int(temp / 2)
cnt_2 -= 1
while remain % 5 == 0 and cnt_5 > 0:
remain = int(remain / 2)
temp = int(temp / 5)
cnt_5 -= 1
comp = 10 ** max(cnt_2, cnt_5) / temp
# print(cnt_2, cnt_5, temp, temp_b, comp)
remain *= comp
y = int(remain / temp_b)
if y > 0:
y = str(y)
while len(y) < max(cnt_2, cnt_5):
y = '0' + y
else:
y = ''
found = find(temp_b)
remain = (remain % temp_b) * found[0]
z = str(int(remain))
while (len(z) < found[1]):
z = '0' + z
print('{0}.{1}({2})'.format(x, y, z))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment