Topic Links:
http://acm.hdu.edu.cn/showproblem.php?pid=1717
Analysis:
We divide this repeating decimal into three parts 0.a1a2a3a4....an (B1B2BB3...BM) into 0, non-cyclic part a1a2...an, and loop section B1B2B3...BM
Set this decimal for X,A1A2A3....AN=S1, b1b2b3...bm=s2,y=0. (B1B2B3B4. Bm
X * 10^n = s1 + y; ---------1)
Y * 10^m = s2 + y; ----------2)
by 2) y = s2/(10^m-1); ------------3)
1), 3) United
x= (s2 + s1 * (10^m-1))/(10^n * (10^m-1));
Pay attention to m=0, or n=0, when dealing with the situation
The code is as follows:
#include <iostream> #include <cmath> #include <cstdio> #include <cstring>using namespace std; typedef long Long LL; ll GCD (ll A,ll b) {if (b) return gcd (b,a%b); return A;} Char A[10000];int main () {int n; scanf ("%d", &n); while (n--) {scanf ("%s", a); LL z1 = 0,cnt=0,m=0,cnt2=0,ff=100000,z2=0; for (int i=1;i<strlen (a); i++) {if (a[i]!= '. ') &&a[i]!= ' (' &&i<ff) {z1=z1*10+a[i]-' 0 '; if (I<FF) cnt++; } if (a[i]== ' (') ff=i; if (i>ff&&a[i]!= ') ') z2=z2*10+a[i]-' 0 ', cnt2++; } LL tmp1=1,tmp2=1,tmp,z; for (int i=0;i<cnt;i++) tmp1*=10; for (int i=0;i<cnt2;i++) tmp2*=10; if (tmp1==1) {z=z2; m=tmp2-1; TMP=GCD (Z,M); printf ("%i64d/%i64d\n", z/tmp,m/tmp); Continue } if (tmp2==1) {z=z1,m=tmp1; TMP=GCD (Z,M); printf ("%i64d/%i64d\n", z/tmp,m/tmp); Continue } z=z2+ (tmp2-1) *z1; M=tmp1* (tmp2-1); TMP=GCD (Z,M); printf ("%i64d/%i64d\n", z/tmp,m/tmp); } return 0;}
HDU1717 (repeating decimal fraction)