#154 · Math · Advanced · 140 XP · about 30 min
Some fractions have short decimals (1/4 = 0.25), and others repeat forever (1/3 = 0.333...). A repeating decimal can still be written exactly by putting the repeating block in parentheses: 1/3 is 0.(3) and 1/6 is 0.1(6).
Write fraction_to_decimal(numerator, denominator) that returns the exact decimal of numerator / denominator as a string:
'2', '-3', '0').., then the digits after the point, with the repeating block (if there is one) in parentheses. Use the shortest repeating block, starting as early as possible.- in front when the result is negative.fraction_to_decimal(1, 4) # returns '0.25' fraction_to_decimal(4, 333) # returns '0.(012)' fraction_to_decimal(-22, 7) # returns '-3.(142857)' fraction_to_decimal(6, -3) # returns '-2'
4/333 = 0.012012012..., so the block 012 repeats from the first digit after the point.
denominator is never 0Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.