Advertisement
TermSpar

C++ Reduce Fractions

Oct 12th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. using namespace std;
  6.  
  7. long gcd(long, long);
  8. string doFrac(double, double);
  9. int countDigits(double);
  10.  
  11. int main(){
  12.   cout << doFrac(66,20);
  13. }
  14.  
  15. long gcd(long a, long b){
  16.     if (a == 0)
  17.         return b;
  18.     else if (b == 0)
  19.         return a;
  20.  
  21.     if (a < b)
  22.         return gcd(a, b % a);
  23.     else
  24.         return gcd(b, a % b);
  25. }
  26.  
  27. string doFrac(double num, double denom){
  28.     ostringstream s;
  29.     string re;
  30.     double dec;
  31.     long gcd_;
  32.    
  33.     dec = num / denom;
  34.    
  35.     if(countDigits(dec) < 7){
  36.         dec *= 100;
  37.         gcd_ = gcd(dec, 100);
  38.    
  39.         dec /= gcd_;
  40.         int dec2 = dec;
  41.         double temp = 100 / gcd_;
  42.         s << dec2; s << "/"; s << temp;
  43.         re = s.str();
  44.         return re;
  45.     } else {
  46.         int nDec = 0;
  47.         int nine = 0;
  48.         if(gcd(num, denom) == 1){
  49.             s << num; s << "/"; s << denom;
  50.             re = s.str();
  51.             return re;
  52.         } else {
  53.             dec *= 10;
  54.             nDec = dec;
  55.             nine = 9 /gcd(nDec, 9);
  56.             nDec /= gcd(nDec, 9);
  57.             s << nDec; s << "/"; s << nine;
  58.             re = s.str();
  59.             return re;
  60.         }
  61.     }
  62. }
  63.  
  64. int countDigits(double d){
  65.     ostringstream s1;
  66.     string s2;
  67.     s1 << d;
  68.     s2 = s1.str();
  69.     int num;
  70.     for(int i = 0; i < s2.size(); i++){
  71.         num++;    
  72.     }
  73.     return abs(num);
  74. }
  75. int countDigits(int d){
  76.     ostringstream s1;
  77.     string s2;
  78.     s1 << d;
  79.     s2 = s1.str();
  80.     int num;
  81.     for(int i = 0; i < s2.size(); i++){
  82.         num++;    
  83.     }
  84.     return num;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement