This question doesn't need to apply to just terminating decimals - repeating decimals can also be converted to fractions via an algorithm.
Your task is to make a program that takes a repeated decimal as input, and output the corresponding numerator and denominator (in lowest terms) that produces that decimal expansion. Fractions greater than 1 should be represented as improper fractions like 9/5
. You can assume that input will be positive.
The repeated decimal will be given in this format:
5.3.87
with everything after the second dot repeated, like this:
5.3878787878787...
Your program will output two integers representing the numerator and denominator, separated by a slash (or the equivalent form in your language if you do not output plain text):
889/165
Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots.
Test cases
These test cases cover all of the required corner cases:
0..3 = 1/3
0.0.3 = 1/30
0.00.3 = 1/300
0.6875. = 11/16
1.8. = 9/5
2.. = 2/1
5..09 = 56/11
0.1.6 = 1/6
2..142857 = 15/7
0.01041.6 = 1/96
0.2.283950617 = 37/162
0.000000.1 = 1/9000000
0..9 = 1/1
0.0.9 = 1/10
0.24.9 = 1/4
If you wish, you can also assume that fractions without integer parts have nothing to the left of the first dot. You can test that with these optional test cases:
.25. = 1/4
.1.6 = 1/6
..09 = 1/11
.. = 0/1
9/99
)? \$\endgroup\$(in lowest terms)
i.e. the fraction must be simplified. \$\endgroup\$13
instead of13/1
? \$\endgroup\$1.9999...
and output2/1
\$\endgroup\$1.9999.
is19999/10000
, to get2/1
you need1..9
, isn't it? \$\endgroup\$