Decimal to Fraction

Interview

Time limit1sMemory limit128 MB

Summary
Convert a decimal string, with an optional repeating block in parentheses, into the exact fraction in lowest terms.
Level

Medium5 of 10

Topics
Math, Number theory, String, Implementation
Solved
No attempts yet

Problem

When a rational number is written as a decimal, there are two cases: the decimal has finitely many digits after the point (for example, 1/8=0.1251/8 = 0.125), or from some position onward a fixed block of digits repeats forever (for example, 1/11=0.090909…1/11 = 0.090909\ldots).

Given such a decimal, write a program that expresses it as a fraction in lowest terms.

Input

The first line contains the number of test cases, which is at most 100100. Each of the following lines contains one decimal.

Every decimal begins with 0.. After that come 00 to 66 digits, followed by an optional number wrapped in parentheses. The number inside the parentheses has length between 11 and 99 and denotes the block of digits that repeats forever.

Each decimal always contains at least one nonzero digit, and the number inside the parentheses is never made up entirely of 00s or entirely of 99s.

Output

For each test case, print the fraction representation of the given decimal on its own line. The numerator and denominator must be coprime (the fraction must be in lowest terms).

Examples4

  1. Example 1

    Input
    3
    0.5
    0.(3)
    0.6(142857)
    
    Expected output
    1/2
    1/3
    43/70
    
  2. Example 2

    Input
    5
    0.1
    0.25
    0.125
    0.2
    0.123456
    
    Expected output
    1/10
    1/4
    1/8
    1/5
    1929/15625
    
  3. Example 3

    Input
    4
    0.(1)
    0.(142857)
    0.(6)
    0.(12)
    
    Expected output
    1/9
    1/7
    2/3
    4/33
    
  4. Example 4

    Input
    4
    0.1(6)
    0.16(6)
    0.583(3)
    0.0(3)
    
    Expected output
    1/6
    1/6
    7/12
    1/30