Convert given Float value to equivalent Fraction
Enclosed sequence of digits in “()” in the floating-point representation expresses recurrence in the decimal representation.
For example, 1.(6) represents 1.666….
Input: N = “1.5”
Output: 3 / 2
The value of 3 / 2 will be equal to 1.5
Input: N = “1.(6)”
Output: 5 / 3
The value of 5 / 3 will be equal to 1.666… which is represented as 1.(6).
Approach: The idea is to use the Greatest Common Divisor of two numbers and some mathematical equations to solve the problem. Follow the below steps to solve the problem:
- Let there be x numbers after the decimal except for the recurring sequence.
- If there is no recurring sequence then multiply the given number with 10x and let the GCD of 10x and the resultant number be g. Print resultant divided by g as the numerator and 10x divided by g as the denominator.
For example, if N = “1.5” then x = 1.
Multiplying N with 10, the resultant will be 15 and the GCD of 10 and 15 is 3.
Therefore, print 15/3 = 5 as the numerator and 10/5 as the denominator.
- If the recurrence sequence is present, then multiply N with 10x. For example, if N = 23.98(231) multiply it with N*(102).
- Let the total number of digits in a sequence be y. For 102*N = 2398.(231), y becomes 3.
- Multiply 10y with N*10x. For 102*N = 2398.(231), multiply it with 103 i.e., 102*N*103 = 2398231.(231).
- Now, subtract, N*10y+x with N*10x and let the result be M. For the above example, 102*N*(103-1) = 2395833.
- Therefore, N = M / ((10x)*(10y – 1)). For the above example, N = 2395833 / 999000.
- Find the GCD of M and ((10x)*(10y – 1)) and print M / gcd as the numerator and ((10x)*(10y – 1)) as the denominator.
Below is the implementation of the above approach:
798611 / 33300
Time Complexity: O(log10N)
Auxiliary Space: O(1)