📜  以字符串格式表示两个数字的分数

📅  最后修改于: 2021-04-26 07:17:50             🧑  作者: Mango

给定两个表示分数的分子和分母的整数,以字符串格式返回分数。如果小数部分是重复的,则将重复的部分括在括号中。

例子:

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.

先决条件:分数中的重复序列

方法:想法是首先计算积分商(小数点前的绝对部分),然后计算小数部分。要检查小数部分是否重复,请在映射中插入余数(分子%分母),其中键为余数,值为发生此余数的索引位置。如果在任何时间点,余数变为零,则不存在重复分数;否则,如果在映射中已找到余数,则存在重复分数。

下面是上述方法的实现。

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 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.util.*;
 
class GFG {
 
    // Function to return the required fraction
    // in string format
 
    public static String calculateFraction(int num, int den)
    {
        if (num == 0)
            return "0"; // if numerator is zero
        if (den == 0)
            return ""; // if denominator is zero
 
        // result StringBuilder
 
        StringBuilder result = new StringBuilder();
        if ((num < 0) ^ (den < 0))
            result.append("-"); // check -ve sign
 
        // absoulte values of num and den
 
        num = Math.abs(num);
        den = Math.abs(den);
 
        long quo = num / den; // Quotient
        long rem = num % den * 10; // calculating remainder
 
        result.append(
            String.valueOf(quo)); // appending quotient
        if (rem == 0)
            return result
                .toString(); // return if remainder is 0
 
        // if remainder is not zero, continue
 
        result.append(".");
        Map m
            = new HashMap<>(); // map for storing remainder
                               // and the indexes of the
                               // appropriate decimal in
                               // stringbuilder
 
        while (rem != 0) {
 
            if (m.containsKey(rem)) {
 
                // if the rem is already present, find the
                // index and append ( )
 
                int index = m.get(rem);
                String part1 = result.substring(0, index);
                String part2 = "("
                               + result.substring(
                                   index, result.length())
                               + ")";
                return part1 + part2;
            }
 
            // continue updating the map and appending quo
            // which was generated by dividing rem with den
 
            m.put(rem, result.length());
            quo = rem / den;
            result.append(String.valueOf(quo));
 
            // update rem
            rem = (rem % den) * 10;
        }
        return result.toString();
    }
 
    // Driver code
    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);
    }
}
 
// This code is contributed by Saiteja Marisetti


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)


输出:
2.(27)
-0.5