Given a fraction Convert into a decimal. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday 10 July 2019

Given a fraction Convert into a decimal.

Given a fraction. Convert it into a decimal. So simple :P
eg.
10/2 = 5
3/5 = 0.6
(The Question Begins Now)  :D
If the decimals are repeating recursively, then enclose them inside  ().
eg.
8/3 = 2.(6)
as 8/3 = 2.66666666.......  infinitly.   
Let us simulate the process of converting fraction to decimal. Let us look at the part where we have already figured out the integer part which is floor(numerator/denominator). Now we are left with      ( remainder = numerator%denominator ) / denominator.
If you remember the process of converting to decimal, at each step we do the following :
  1. Multiply the remainder by 10.
  2. Append remainder / denominator to result.
  3. Remainder = remainder % denominator.
At any moment, if remainder becomes 0, we are done.
However, when there is a recurring sequence, remainder never becomes 0. For example if you look at 1/3, the remainder never becomes 0.
Below is one important observation :
If we start with remainder ‘rem’ and if the remainder repeats at any point of time, the digits between the two occurrence of ‘rem’ keep repeating.
  


#include <bits/stdc++.h> 
using namespace std; 
void fractionToDecimal(int numr, int denr) 
    string res; 
  
    // Create a map to store already seen remainders 
    // remainder is used as key and its position in 
    // result is stored as value. Note that we need 
    // position for cases like 1/6.  In this case, 
    // the recurring sequence doesn't start from first 
    // remainder. 
    map <int, int> mp; 
    mp.clear(); 
  
    // Find first remainder 

    int rem = numr%denr; 
  
    // Keep finding remainder until either remainder 

    // becomes 0 or repeats 

    while ( (rem!=0) && (mp.find(rem) == mp.end()) ) 
    { 
        // Store this remainder 

        mp[rem] = res.length(); 
  
        // Multiply remainder with 10 

        rem = rem*10; 
  
        // Append rem / denr to result 
        int res_part = rem / denr; 
        res += to_string(res_part); 
  
        // Update remainder 
        rem = rem % denr; 
    } 
  
     (rem == 0)? cout<<(double)numr/denr<<endl : cout<<(numr/denr)<<"." <<(res.substr(0,mp[rem]))<<"("<<res.substr(mp[rem])<<")"<<endl; 
  
int main() 
    int t;
cin>>t;
while(t--){

    int numr, denr; 
    cin>>numr;
    cin>>denr;
    fractionToDecimal(numr, denr); 

            }
    return 0;