Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Compute 'lengths' before compute decimals solution in Clear category for Repeating Decimals by Phil15
from math import gcd
def period_length(n):
"""Compute length of period of 1/n decimals,
and length between coma and period start.
"""
N, n2, n5 = n, 0, 0
while N%2==0:
N //= 2
n2 += 1
while N%5==0:
N //= 5
n5 += 1
if N==1:
return max(n2,n5), 0
ord = 1
while (10**ord)%N!=1:
ord += 1
return max(n2,n5), ord
def convert(m,n):
"""Write fraction m/n into decimals with periodic decimals between parentheses."""
if m==0:
return '0.'
m, n = m//gcd(m,n), n//gcd(m,n) #Irreducible fraction
#Length of periodic decimals, and length between coma and period start.
pre_period, period = period_length(n)
res, m = str(m//n)+'.', m%n
for k in range(pre_period): #Between coma and period, the "pre_period"
res += str((10*m)//n)
m = (10*m)%n
if period>0: #Period between parentheses.
res += '('
for k in range(period):
res += str((10*m)//n)
m = (10*m)%n
res += ')'
return res
if __name__ == '__main__':
assert convert(1, 3) == "0.(3)", "1/3 Classic"
assert convert(5, 3) == "1.(6)", "5/3 The same, but bigger"
assert convert(3, 8) == "0.375", "3/8 without repeating part"
assert convert(7, 11) == "0.(63)", "7/11 prime/prime"
assert convert(29, 12) == "2.41(6)", "29/12 not and repeating part"
assert convert(11, 7) == "1.(571428)", "11/7 six digits"
assert convert(0, 117) == "0.", "Zero"
March 30, 2018