runnig

Rational to String

Feb 15th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <string>
  2. #include <vector>
  3. #include <stdio.h>
  4. #include <unordered_map>
  5. #include <sstream>
  6. #include <iostream>
  7.  
  8. using namespace std;
  9. string rational_to_string(int numerator, int denom)
  10. {
  11.     std::stringstream ss;
  12.  
  13.     if(denom == 0)
  14.     {
  15.         ss << ((numerator < 0) ? '-' : '+') << "INF";
  16.         return ss.str();
  17.     }
  18.     const bool negative = (numerator * denom < 0);
  19.     if(negative) { ss << '-'; }
  20.  
  21.     float n(std::abs(numerator)), d(std::abs(denom));
  22.    
  23.     int integer_part;
  24.     if(n < d)
  25.     {
  26.         integer_part = 0;
  27.     }
  28.     else
  29.     {
  30.         integer_part = int(n/d);
  31.         n -= float(integer_part) * d;
  32.     }
  33.     ss << integer_part;
  34.  
  35.     typedef unordered_map<int, int> num_pos_map_t;
  36.     num_pos_map_t prev_numerators;
  37.  
  38.     vector<int> frac_digits;
  39.  
  40.     size_t period_begin = INT_MAX, period_end = INT_MAX;
  41.  
  42.     for(size_t pos = 0; n > 0; ++pos)
  43.     {
  44.         num_pos_map_t::iterator it;
  45.         if((it = prev_numerators.find(n)) != prev_numerators.end())
  46.         {
  47.             period_begin = it->second;
  48.             period_end = pos;
  49.             break;
  50.         }
  51.         prev_numerators[n] = pos;
  52.         n *= 10.0f;
  53.  
  54.         int digit = int(n/d);
  55.         frac_digits.push_back(digit);
  56.  
  57.         n -= digit * d;
  58.     }
  59.  
  60.  
  61.     if(!frac_digits.empty())
  62.     {
  63.         ss << '.';
  64.         size_t i;
  65.         for(i = 0; i < frac_digits.size(); ++i)
  66.         {
  67.             if(i == period_begin)
  68.             {
  69.                 ss << '(';
  70.             }
  71.             ss << frac_digits[i];
  72.         }
  73.  
  74.         if(i >= period_end)
  75.         {
  76.             ss << ')';
  77.         }
  78.     }
  79.  
  80.     return ss.str();
  81. }
  82.  
  83. int main(int argc, char* argv[])
  84. {
  85.     std::cout << rational_to_string(0,0) << '\n';
  86.     std::cout << rational_to_string(0,1) << '\n';
  87.     std::cout << rational_to_string(-1,0) << '\n';
  88.     std::cout << rational_to_string(5,3) << '\n';
  89.     std::cout << rational_to_string(-5,3) << '\n';
  90.     std::cout << rational_to_string(-5,-3) << '\n';
  91.     std::cout << rational_to_string(3227,555) << '\n';
  92.     std::cout << rational_to_string(13,720) << '\n';
  93.     std::cout << rational_to_string(-1,57) << '\n';
  94.  
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment