Given two integers representing the Numerator and Denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses.
Input: Numerator = 1, Denominator = 2 Output: "0.5" 1/2 = 0.5 with no repeating part. Input: Numerator = 50, Denominator = 22 Output: "2.(27)" 50/22 = 2.27272727... Since fractional part (27) is repeating, it is enclosed in parentheses.
Prerequisites :Recurring Sequence in a Fraction
Approach: The idea is to first calculate the integral quotient (absolute part before decimal point) and then calculate the fractional part. To check if the fractional part is repeating, insert the remainder (numerator % denominator) in a map with key as remainder and value as the index position at which this remainder occurs. If at any point of time, the remainder becomes zero, then there doesn’t exist a repeating fraction otherwise if the remainder is already found in the map, then there exists a repeating fraction.
Below is the implementation of above approach.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find ΔX which is added to numerator and denominator both of fraction (a/b) to convert it to another fraction (c/d)
- Find the Nth digit in the proper fraction of two numbers
- Add two integers of different base and represent sum in smaller base of the two
- Represent the given number as the sum of two composite numbers
- Greedy Algorithm for Egyptian Fraction
- Convert decimal fraction to binary number
- Fraction module in Python
- Largest proper fraction with sum of numerator and denominator equal to a given number
- as_integer_ratio() in Python for reduced fraction of a given rational
- First occurrence of a digit in a given fraction
- Maximum rational number (or fraction) from an array
- Expressing a fraction as a natural number under modulo 'm'
- Print first N terms of series (0.25, 0.5, 0.75, ...) in fraction representation
- Reduce the fraction to its lowest form
- Find N fractions that sum upto a given fraction N/D
- Max count of unique ratio/fraction pairs in given arrays
- Convert given Decimal number into an irreducible Fraction
- Convert Binary fraction to Decimal
- Find Recurring Sequence in a Fraction
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.