Python coding

Fraction as a repeating decimal

Given two integers numerator and denominator (denominator is not 0), return their quotient as a decimal string. When the digits after the point repeat forever, put the repeating block, and only that block, in parentheses: 1/3 is "0.(3)" and 1/6 is "0.1(6)". A whole result has no point ("2"), a finite one ends at its last nonzero digit ("0.25"), and a negative one starts with -; zero is just "0".

The repeating block can be thousands of digits long: aim for time proportional to the digits you write.

Besides the tests, one large input (a 12,010-digit cycle) with a ~220 ms limit (scaled to your device's speed): brute force won't pass.

  • to_decimal(1, 4) → "0.25"
  • to_decimal(6, 3) → "2"
  • to_decimal(5, 37) → "0.(135)"
  • to_decimal(1, 6) → "0.1(6)"
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Do the long division you learned at school: each step multiplies the remainder by 10 and writes one digit. Everything that follows depends only on the current remainder.

Hint 2

Map each remainder to the position of the digit it produces. When a remainder comes back, the digits repeat from its stored position; a remainder of 0 means the decimal ends.

Hint 3

Settle the sign first: divide the absolute values, and add - only when exactly one input is negative and the numerator is not 0.

Solution and why it works
pythonO(k), k = digits after the point (k < |denominator|) · O(k)
def to_decimal(numerator: int, denominator: int) -> str:
    sign = "-" if numerator != 0 and (numerator < 0) != (denominator < 0) else ""
    n, d = abs(numerator), abs(denominator)
    whole, rem = divmod(n, d)
    if rem == 0:
        return f"{sign}{whole}"
    digits, seen = [], {}            # remainder -> index of the digit it produces
    while rem and rem not in seen:
        seen[rem] = len(digits)
        rem *= 10
        digits.append(str(rem // d))
        rem %= d
    if rem:                          # a remainder came back: the digits repeat from there
        start = seen[rem]
        digits.insert(start, "(")
        digits.append(")")
    return f"{sign}{whole}." + "".join(digits)

Each digit of a long division depends only on the current remainder, and there are fewer than denominator of them, so either a remainder hits 0 (the decimal ends) or one comes back and everything after it repeats. A map from remainder to digit position spots the return in O(1) and says exactly where the parenthesis opens. Searching a list of seen remainders costs O(k) per digit: quadratic on long cycles. Trap: settle the sign on absolute values, so -1/3 is -0.(3) and 0/-5 is 0.

Related lab: Loops in motion