# Represent the fraction of two numbers in the string format

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.

Examples:

```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.

## C++

 `// C++ program to calculate ` `// fraction of two numbers` `#include ` `using` `namespace` `std;`   `// Function to return the required fraction` `// in string format` `string calculateFraction(``int` `num, ``int` `den)` `{` `    ``// If the numerator is zero, answer is 0` `    ``if` `(num == 0)` `        ``return` `"0"``;`   `    ``// If any one (out of numerator and denominator)` `    ``// is -ve, sign of resultant answer -ve.` `    ``int` `sign = (num < 0) ^ (den < 0) ? -1 : 1;`   `    ``num = ``abs``(num);` `    ``den = ``abs``(den);`   `    ``// Calculate the absolute part (before decimal point).` `    ``int` `initial = num / den;`   `    ``// Output string to store the answer` `    ``string res;`   `    ``// Append sign` `    ``if` `(sign == -1)` `        ``res += ``"-"``;`   `    ``// Append the initial part` `    ``res += to_string(initial);`   `    ``// If completely divisible, return answer.` `    ``if` `(num % den == 0)` `        ``return` `res;`   `    ``res += ``"."``;`   `    ``// Initialize Remainder` `    ``int` `rem = num % den; ` `    ``map<``int``, ``int``> mp;`   `    ``// Position at which fraction starts repeating` `    ``// if it exists` `    ``int` `index;` `    ``bool` `repeating = ``false``;` `    ``while` `(rem > 0 && !repeating) {`   `        ``// If this remainder is already seen,` `        ``// then there exists a repeating fraction.` `        ``if` `(mp.find(rem) != mp.end()) {`   `            ``// Index to insert parentheses` `            ``index = mp[rem];` `            ``repeating = ``true``;` `            ``break``;` `        ``}` `        ``else` `            ``mp[rem] = res.size();`   `        ``rem = rem * 10;`   `        ``// Calculate quotient, append it to result and` `        ``// calculate next remainder` `        ``int` `temp = rem / den;` `        ``res += to_string(temp);` `        ``rem = rem % den;` `    ``}`   `    ``// If repeating fraction exists, insert parentheses.` `    ``if` `(repeating) {` `        ``res += ``")"``;` `        ``res.insert(index, ``"("``);` `    ``}`   `    ``// Return result.` `    ``return` `res;` `}`   `// Drivers Code` `int` `main()` `{` `    ``int` `num = 50, den = 22;` `    ``cout << calculateFraction(num, den) << endl;`   `    ``num = -1, den = 2;` `    ``cout << calculateFraction(num, den) << endl;` `    ``return` `0;` `}`

## Java

 `// Java program to calculate fraction ` `// of two numbers` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG{` `    `  `  `  `// Function to return the required fraction ` `// in string format ` `public` `static` `String calculateFraction(``int` `num,` `                                       ``int` `den)` `{` `    `  `    ``// If the numerator is zero, answer is 0 ` `    ``if` `(num == ``0``)` `        ``return` `"0"``;` `        `  `    ``// Divide by zero exception, ` `    ``// hence invalid` `    ``if` `(den == ``0``)` `        ``return` `"Invalid"``;` `        `  `    ``// Check the numerator or ` `    ``// denominator is negative` `    ``boolean` `neg = ``false``;` `    ``if` `(num < ``0` `|| den <``0``)` `        ``neg = ``true``;` `        `  `    ``// If the denominator divides` `    ``// the numerator with remainder` `    ``// as zero` `    ``if` `(num % den == ``0``)` `    ``{` `        ``int` `res1 = (num / den);` `        ``return` `Integer.toString(res1);` `    ``}` `    `  `    ``// Arraylist to store the numbers` `    ``// after the decimal point` `    ``ArrayList Fraction = ``new` `ArrayList<>();` `    `  `    ``// String Builder for returning the ` `    ``// result in string format with ` `    ``// specific format` `    ``StringBuilder str = ``new` `StringBuilder();` `    `  `    ``// If the numerator or denominator` `    ``// is negative the result will be ` `    ``// negative, hence append the string` `    ``// with "-" at beginning` `    ``if` `(neg == ``true``)` `    ``{` `        ``str.append(``"-"``);` `    ``}` `    `  `    ``// Taking only the absolute values ` `    ``// from the numerator and denominator ` `    ``num = Math.abs(num);` `    ``den = Math.abs(den);` `    `  `    ``// Appending the number before` `    ``// the decimal point` `    ``str.append(num / den);` `    `  `    ``// Decimal point` `    ``str.append(``"."``);` `    ``while``(``true``)` `    ``{` `        `  `        ``// Calculating remainder` `        ``int` `rem = num % den;` `        `  `          ``// The remainder becomes zero, ` `          ``// then the result will have no ` `          ``// recurring digits after decimal point` `        ``if` `(rem == ``0``)` `        ``{` `            ``for``(``int` `i = ``0``;i < Fraction.size(); i++) ` `            ``{` `                ``str.append(Fraction.get(i));` `            ``}` `            ``break``;` `        ``}` `        `  `        ``// The numerator for next iteration ` `        ``// will be the product of remainder` `        ``// and 10` `        ``num = rem * ``10``;` `        `  `        ``// Calculating quotient ` `        ``int` `quo = num / den;` `        `  `        ``// Adding the digit to the Fraction` `        ``// list only if it does not exists in it` `        ``if` `(!(Fraction.contains(quo))) ` `        ``{` `            ``Fraction.add(quo);` `        ``}` `        `  `        ``// If the quotient exists in the Fraction list` `        ``else` `if``(Fraction.contains(quo)) ` `        ``{` `            `  `            ``// Retrieving the index of the` `            ``// number upto which the quotient` `            ``// is not recurring` `            ``int` `ind = Fraction.indexOf(quo);` `            ``for``(``int` `i = ``0``; i <= ind - ``1``; i++)` `            ``{` `                ``str.append(Fraction.get(i));` `            ``}` `            `  `            ``// Printing the recurring pattern` `            ``// within brackets` `            ``str.append(``"("``);` `            ``for``(``int` `i = ind; i < Fraction.size(); i++)` `            ``{` `                ``str.append(Fraction.get(i));` `            ``}` `            ``str.append(``")"``);` `            ``break``;` `        ``}` `    ``}` `    `  `    ``// Convert str to String and` `    ``// return the result` `    ``return` `str.toString();` `}`   `// Driver code` `public` `static` `void` `main (String[] args)` `{` `    ``int` `num = ``50``;` `    ``int` `den = ``22``;` `    `  `    ``String resString1 = calculateFraction(num, den);` `    `  `    ``num = -``1``;` `    ``den = ``2``;` `    `  `    ``String resString2 = calculateFraction(num, den);` `    `  `    ``System.out.println(resString1);` `    ``System.out.println(resString2);` `}` `}`   `// This code is contributed by Hithesh Kumar C M` `// hitheshkumarcm33309`

## Python3

 `# Python3 program to calculate fraction ` `# of two numbers`   `# Function to return the required ` `# fraction in string format ` `def` `calculateFraction(num, den) :`   `    ``# If the numerator is zero, answer is 0 ` `    ``if` `(num ``=``=` `0``): ` `        ``return` `"0"`   `    ``# If any one (out of numerator and denominator) ` `    ``# is -ve, sign of resultant answer -ve. ` `    ``sign ``=` `-``1` `if` `(num < ``0``) ^ (den < ``0``) ``else` `1`   `    ``num ``=` `abs``(num) ` `    ``den ``=` `abs``(den) `   `    ``# Calculate the absolute part ` `    ``# (before decimal point). ` `    ``initial ``=` `num ``/``/` `den `   `    ``# Output string to store the answer ` `    ``res ``=` `"" `   `    ``# Append sign ` `    ``if` `(sign ``=``=` `-``1``): ` `        ``res ``+``=` `"-"`   `    ``# Append the initial part ` `    ``res ``+``=` `str``(initial) `   `    ``# If completely divisible, return answer. ` `    ``if` `(num ``%` `den ``=``=` `0``): ` `        ``return` `res `   `    ``res ``+``=` `"."`   `    ``# Initialize Remainder ` `    ``rem ``=` `num ``%` `den ` `    ``mp ``=` `{} `   `    ``# Position at which fraction starts` `    ``# repeating if it exists ` `    ``index ``=` `0` `    ``repeating ``=` `False` `    ``while` `(rem > ``0` `and` `not` `repeating) :`   `        ``# If this remainder is already seen, ` `        ``# then there exists a repeating fraction. ` `        ``if` `( rem ``in` `mp): `   `            ``# Index to insert parentheses ` `            ``index ``=` `mp[rem] ` `            ``repeating ``=` `True` `            ``break` `        `  `        ``else``:` `            ``mp[rem] ``=` `len``(res) `   `        ``rem ``=` `rem ``*` `10`   `        ``# Calculate quotient, append it to result ` `        ``# and calculate next remainder ` `        ``temp ``=` `rem ``/``/` `den ` `        ``res ``+``=` `str``(temp )` `        ``rem ``=` `rem ``%` `den ` `    `  `    ``# If repeating fraction exists, ` `    ``# insert parentheses. ` `    ``if` `(repeating) : ` `        ``res ``+``=` `")"` `        ``x ``=` `res[:index]` `        ``x ``+``=` `"("` `        ``x ``+``=` `res[index:]` `        ``res ``=` `x` `    `  `    ``# Return result. ` `    ``return` `res `   `# Driver code ` `if` `__name__ ``=``=``"__main__"``:` `    ``num ``=` `50` `    ``den ``=` `22` `    ``print``(calculateFraction(num, den))` `    ``num ``=` `-``1` `    ``den ``=` `2` `    ``print``(calculateFraction(num, den)) `   `# This code is contributed` `# Shubham Singh(SHUBHAMSINGH10)`

Output:

```2.(27)
-0.5

```

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.

My Personal Notes arrow_drop_up A Coding Enthusiast Rails Developer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.

Article Tags :
Practice Tags :

9

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.