Fraction to Repeating Decimal
InterviewTime limit1sMemory limit256 MB
Write each given fraction as its decimal form with the shortest nonrepeating part and the repeating block in parentheses.
- Level
Medium5 of 10
- Topics
- Hash map, Math, Simulation
- Solved
- No attempts yet
Problem
Every rational number can be written as a repeating decimal, where from some position on the same block of digits repeats forever.
The denominators above are made of nothing but 9s and 0s, and that pattern is exactly the standard recipe for turning a repeating decimal back into a fraction. Starting from an arbitrary fraction, that recipe is hard to apply, so the usual way to convert a fraction into a repeating decimal is repeated long division. Doing it by hand takes a lot of work, so write a program that does it for you.
Input
The first line contains the number of test cases ().
Each of the next lines contains a numerator and a denominator as integers separated by a space, with and .
Output
For each test case, print the repeating decimal of on its own line.
Write the integer part, a period, the non-repeating fractional digits, then the repeating block wrapped in parentheses. When the non-repeating part is empty, the opening parenthesis comes right after the period. A fraction whose division comes out even still gets , because zeros repeat forever after the last digit. Take the shortest possible non-repeating part and the shortest possible repeating block.