def todecstr(n): import decimal D = decimal.Decimal D2 = D(2) BITLIM = 128 def inner(n, w): if w <= BITLIM: return D(n) w2 = w >> 1 hi = n >> w2 lo = n - (hi << w2) return inner(hi, w - w2) * w2pow[w2] + inner(lo, w2) with decimal.localcontext() as ctx: ctx.prec = decimal.MAX_PREC ctx.Emax = decimal.MAX_EMAX ctx.Emin = decimal.MIN_EMIN ctx.traps[decimal.Inexact] = 1 w2pow = {} w = n.bit_length() while w >= BITLIM: w2 = w >> 1 if w & 1: w2pow[w2 + 1] = None w2pow[w2] = None w = w2 if w2pow: it = reversed(w2pow.keys()) w = next(it) w2pow[w] = D2 ** w for w in it: if w - 1 in w2pow: val = w2pow[w - 1] * D2 else: w2 = w >> 1 assert w2 in w2pow assert w - w2 in w2pow val = w2pow[w2] * w2pow[w - w2] w2pow[w] = val #print(w2pow.keys()) return str(inner(n, n.bit_length())) if 1: for bl in range(1, 10001): if bl % 1000 == 0: print(f"{bl = :,}") n = (1 << bl) - 1 got = todecstr(n) assert got == str(n)