1876: [SDOI2009]SUPERGCD time limit:4 Sec Memory limit:64 MB
submit:1970 solved:663
[Submit] [Status] [Discuss] Descriptionsheng Bill has an amazing mental arithmetic ability, and can even use the brain to figure out two huge numbers of gcd (greatest common divisor)! So he often contests with others to calculate gcd. One day Sheng Bill very arrogant to find you, and asked to play with you, but lost to Sheng Bill is not very embarrassing! So you decided to write a program to teach him. Input is a total of two lines: the first line: a number A. Second line: a number B. An output row that represents the greatest common divisor of a and B. Sample Input12
54
Sample Output6
HINT
For 20% of data, 0 < A, b≤10 ^ 18.
For 100% of data, 0 < A, b≤10 ^ 10000.
According to the mathematics compulsory Ⅲ, we know that the more subtractive loss of GCD. So the problem is a high-precision exercise ...
#include <iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<cmath>#defineINF 1000000000using namespacestd;Charch1[10005],ch2[10005];intla,lb,cnt;structdata{inta[1205],l;} b;BOOLcom () {if(A.L<B.L)return 0; if(A.L>B.L)return 1; for(intI=a.l;i>0; i--) if(A.a[i]>b.a[i])return 1; Else if(A.a[i]<b.a[i])return 0; return 1;}voidprint (Data a) { while(a.a[a.l]==0) a.l--; for(intI=a.l;i>0; i--) if(I==A.L) printf ("%d", A.a[i]); Elseprintf"%09d", A.a[i]);} Data sub (data A,data b) {intk; Data c; for(intI=1; i<= -; i++) { if(I<=B.L) c.a[i]=a.a[i]-B.a[i]; Else if(I<=A.L) c.a[i]=A.a[i]; Elsec.a[i]=0; if(c.a[i]<0) {C.a[i]+=inf; A.a[i+1]--; }} C.L=A.L; while(c.a[c.l]==0&&C.L) c.l--; returnC;}voidDiva () { for(intI=1; i<=a.l;i++) { if(a.a[i]&1) a.a[i-1]+=inf/2; A.a[i]>>=1; } if(!A.A[A.L]) a.l--;}voidDIVB () { for(intI=1; i<=b.l;i++) { if(b.a[i]&1) b.a[i-1]+=inf/2; B.a[i]>>=1; } if(!B.A[B.L]) b.l--;}voidMul () { for(intI=a.l;i>0; i--) {A.a[i]<<=1; A.a[i+1]+=a.a[i]/inf; A.a[i]%=inf; } while(a.a[a.l]>0) a.l++; for(intI=b.l;i>0; i--) {B.a[i]<<=1; B.a[i+1]+=b.a[i]/inf; B.a[i]%=inf; } while(b.a[b.l]>0) b.l++;}intMain () {scanf ("%s%s", ch1+1, ch2+1); La=strlen (ch1+1); Lb=strlen (ch2+1); if(la%9) a.l=la/9+1;Elsea.l=la/9; if(lb%9) b.l=lb/9+1;Elseb.l=lb/9; for(intI=1; i<=a.l;i++) { intK1=max (1, la-i*9+1), k2=la-(i-1)*9; for(intj=k1;j<=k2;j++) a.a[i]=a.a[i]*Ten+ch1[j]-'0'; } for(intI=1; i<=b.l;i++) { intK1=max (1, lb-i*9+1), k2=lb-(i-1)*9; for(intj=k1;j<=k2;j++) b.a[i]=b.a[i]*Ten+ch2[j]-'0'; } while(1) { if((a.a[1]%2==0) && (b.a[1]%2==0)) Diva (), DIVB (), cnt++; Else if(a.a[1]%2==0) diva (); Else if(b.a[1]%2==0) DIVB (); if(COM ()) {A=sub (A, b);if(!A.L) { while(cnt--) Mul (); Print (b); Break;}} Else{b=sub (b,a);if(!B.L) { while(cnt--) Mul (); Print (a); Break;}} } return 0;}
[SDOI2009] [BZOJ1876] supergcd| High Precision | More subtractive loss Surgery