![]() |
VOOZH | about |
Given a decimal number as N, the task is to convert N into an equivalent irreducible fraction.
An irreducible fraction is a fraction in which numerator and denominator are co-primes i.e., they have no other common divisor other than 1.
Examples:
Input: N = 4.50
Output: 9/2
Explanation:
9/2 in decimal is written as 4.5
Input: N = 0.75
Output: 3/4
Explanation:
3/4 in decimal is written as 0.75
Approach: Follow the steps given below to solve the problem.
For example N = 4.50, integral value = 4 and fractional part = 0.50
Consider precision value to be (109) that is precision value = 1000000000
Calculate GCD(0.50 * 109, 109) = 500000000
Calculate numerator = (0.50 * 10^9) / 500000000 = 1 and denominator = 10^9/ 500000000 = 2
Convert mixed fraction into improper fraction that is fraction = ((4 * 2) + 1) / 2 = 9/2
Below is the implementation of the above approach:
9/2
Time complexity: O(log min(a, b))
Auxiliary space: O(1)
Approach 2: Follow the steps given below to solve the problem.
For larger decimal values the float function automatically rounds off the input resulting in an incorrect response
Using inbuilt python libraries doesn't round off the input for example for the below input the decimal value the code above rounds off the input
For example N = "123456789.25252525"
Decimal(N) takes string input and converts it into decimal value = 123456789.25252525
Now we convert the fraction into string using type casting str(493827157010101/4000000)result "493827157010101/4000000"
Below is the implementation of the above approach:
493827157010101/4000000
Time complexity: O(k + log n)
Auxiliary space: O(1)
Explanation:
The time complexity of the decimalToFraction function depends on the length of the input number and the efficiency of the Fraction constructor. In this case, the input number is converted to a Decimal object using the Decimal constructor, which has a time complexity of O(k), where k is the number of digits in the input number. Then, the Fraction constructor is called with the Decimal object, which has a time complexity of O(log n), where n is the value of the input Decimal object. Therefore, the overall time complexity of decimalToFraction is O(k + log n).
The auxiliary space complexity of the decimalToFraction function is O(1), as it only uses a constant amount of additional memory to store the Fraction object and its string representation of it.