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