Tuesday, February 11, 2020

POJ.1930 Dead Fraction

1.Problem
http://poj.org/problem?id=1930

2.Idea
All credit to this.

3.Source
 int gcd(const int a, const int b)  
 {  
      if (b == 0) return a;  
      return gcd(b, a%b);  
 }  
 static char str[1000];  
 int main()  
 {  
      int sum, last, k, c, i, a, b, div, min_b, min_a, length;  
      while (~scanf("%s", str))  
      {  
           if (strlen(str) == 1 && str[0] == '0')  
                break;  
           sum = 0; length = 0; min_b = INT_MAX;  
           for (i = 2; str[i] != '.'; i++)  
           {  
                sum = sum * 10 + str[i] - '0';  
                length++;  
           }  
           c = (int)pow(10.0, length);  
           for (i = 1, last = sum, k = 1; i <= length; i++)  
           {  
                last /= 10; k *= 10; c /= 10;  
                a = sum - last;  
                b = c*(k - 1);  
                div = gcd(a, b);  
                if (b / div < min_b)  
                {  
                     min_a = a / div;  
                     min_b = b / div;  
                }  
           }  
           printf("%d/%d\n", min_a, min_b);  
      }  
      return 0;  
 }  

No comments:

Post a Comment