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++
#include <bits/stdc++.h>
using namespace std;
string calculateFraction( int num, int den)
{
if (num == 0)
return "0" ;
int sign = (num < 0) ^ (den < 0) ? -1 : 1;
num = abs (num);
den = abs (den);
int initial = num / den;
string res;
if (sign == -1)
res += "-" ;
res += to_string(initial);
if (num % den == 0)
return res;
res += "." ;
int rem = num % den;
map< int , int > mp;
int index;
bool repeating = false ;
while (rem > 0 && !repeating) {
if (mp.find(rem) != mp.end()) {
index = mp[rem];
repeating = true ;
break ;
}
else
mp[rem] = res.size();
rem = rem * 10;
int temp = rem / den;
res += to_string(temp);
rem = rem % den;
}
if (repeating) {
res += ")" ;
res.insert(index, "(" );
}
return res;
}
int main()
{
int num = 50, den = 22;
cout << calculateFraction(num, den) << endl;
num = -1, den = 2;
cout << calculateFraction(num, den) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static String calculateFraction( int num, int den)
{
if (num == 0 )
return "0" ;
if (den == 0 )
return "" ;
StringBuilder result = new StringBuilder();
if ((num < 0 ) ^ (den < 0 ))
result.append( "-" );
num = Math.abs(num);
den = Math.abs(den);
long quo = num / den;
long rem = num % den * 10 ;
result.append(
String.valueOf(quo));
if (rem == 0 )
return result
.toString();
result.append( "." );
Map<Long, Integer> m
= new HashMap<>();
while (rem != 0 ) {
if (m.containsKey(rem)) {
int index = m.get(rem);
String part1 = result.substring( 0 , index);
String part2 = "("
+ result.substring(
index, result.length())
+ ")" ;
return part1 + part2;
}
m.put(rem, result.length());
quo = rem / den;
result.append(String.valueOf(quo));
rem = (rem % den) * 10 ;
}
return result.toString();
}
public static void main(String[] args)
{
int num = 113 ;
int den = 56 ;
String resString1 = calculateFraction(num, den);
num = - 1 ;
den = 2 ;
String resString2 = calculateFraction(num, den);
System.out.println(resString1);
System.out.println(resString2);
}
}
|
Python3
def calculateFraction(num, den) :
if (num = = 0 ):
return "0"
sign = - 1 if (num < 0 ) ^ (den < 0 ) else 1
num = abs (num)
den = abs (den)
initial = num / / den
res = ""
if (sign = = - 1 ):
res + = "-"
res + = str (initial)
if (num % den = = 0 ):
return res
res + = "."
rem = num % den
mp = {}
index = 0
repeating = False
while (rem > 0 and not repeating) :
if ( rem in mp):
index = mp[rem]
repeating = True
break
else :
mp[rem] = len (res)
rem = rem * 10
temp = rem / / den
res + = str (temp )
rem = rem % den
if (repeating) :
res + = ")"
x = res[:index]
x + = "("
x + = res[index:]
res = x
return res
if __name__ = = "__main__" :
num = 50
den = 22
print (calculateFraction(num, den))
num = - 1
den = 2
print (calculateFraction(num, den))
|
C#
using System;
using System.Text;
using System.Collections.Generic;
class GFG {
public static string calculateFraction( int num, int den)
{
if (num == 0)
return "0" ;
if (den == 0)
return "" ;
StringBuilder result = new StringBuilder();
if ((num < 0) ^ (den < 0))
result.Append( "-" );
num = Math.Abs(num);
den = Math.Abs(den);
int quo = num / den;
int rem = num % den * 10;
result.Append(
Convert.ToString(quo));
if (rem == 0)
return result
.ToString();
result.Append( "." );
Dictionary< long , int > m
= new Dictionary< long , int >();
while (rem != 0) {
if (m.ContainsKey(rem)) {
int index = m[rem];
string part1 = result.ToString(0, index);
string part2 = "("
+ result.ToString(index, result.Length - index)
+ ")" ;
return part1 + part2;
}
m[rem] = result.Length;
quo = rem / den;
result.Append(Convert.ToString(quo));
rem = (rem % den) * 10;
}
return result.ToString();
}
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);
Console.WriteLine(resString1);
Console.WriteLine(resString2);
}
}
|
Javascript
<script>
function calculateFraction(num, den)
{
if (num == 0)
return "0" ;
var sign = (num < 0) ^ (den < 0) ? -1 : 1;
num = Math.abs(num);
den = Math.abs(den);
var initial = parseInt(num / den);
var res = [];
if (sign == -1)
res.push( "-" );
res.push(initial.toString());
if (num % den == 0)
return res;
res.push( "." );
var rem = num % den;
var mp = new Map();
var index;
var repeating = false ;
while (rem > 0 && !repeating) {
if (mp.has(rem)) {
index = mp.get(rem);
repeating = true ;
break ;
}
else
mp.set(rem, res.length);
rem = rem * 10;
var temp = parseInt(rem / den);
res.push(temp.toString());
rem = rem % den;
}
if (repeating) {
res.push( ")" );
res.splice(index,0, "(" );
}
return res.join( '' );
}
var num = 50, den = 22;
document.write( calculateFraction(num, den) + "<br>" );
num = -1, den = 2;
document.write( calculateFraction(num, den));
</script>
|
Time Complexity: O(n), where n is the length of the string representation of the output fraction.
Space Complexity: O(n), where n is the length of the string and output string res can store up to n characters, and the map mp can store up to n entries in the worst case where the fraction is repeating.