gcd

迭代法加高精度GCD.

code:

  1 #include
  2 #include
  3 #include
  4 #define inf 1000000000
  5 using namespace std;
  6 char ch1[10005],ch2[10005];
  7 int la,lb,cnt;
  8 struct data{int a[1205],l;}a,b;
  9 bool com()
 10 {
 11     if(a.lreturn 0;
 12     if(a.l>b.l)return 1;
 13     for(int i=a.l;i>0;--i)
 14         if(a.a[i]>b.a[i])return 1;
 15         else if(a.a[i]return 0;
 16     return 1;
 17 }
 18 void print(data a)
 19 {
 20     while(a.a[a.l]==0)a.l--;
 21     for(int i=a.l;i>0;--i)
 22         if(i==a.l)printf("%d",a.a[i]);
 23         else printf("%09d",a.a[i]);
 24 }
 25 inline data sub(data a,data b)
 26 {
 27     int k;
 28     data c;
 29     for(int i=1;i<=1200;++i)
 30     {
 31        if(i<=b.l)c.a[i]=a.a[i]-b.a[i];
 32        else if(i<=a.l)c.a[i]=a.a[i];
 33        else c.a[i]=0;
 34        if(c.a[i]<0)
 35        {
 36           c.a[i]+=inf;
 37           a.a[i+1]--;
 38        }
 39     }
 40     c.l=a.l;
 41     while(c.a[c.l]==0&&c.l)c.l--;
 42     return c;
 43 }
 44 void diva()
 45 {
 46     for(int i=1;i<=a.l;i++)
 47     {
 48         if(a.a[i]&1)a.a[i-1]+=inf/2;
 49         a.a[i]>>=1;
 50     }
 51     if(!a.a[a.l])a.l--;
 52 }
 53 void divb()
 54 {
 55     for(int i=1;i<=b.l;i++)
 56     {
 57         if(b.a[i]&1)b.a[i-1]+=inf/2;
 58         b.a[i]>>=1;
 59     }
 60     if(!b.a[b.l])b.l--;
 61 }
 62 void mul()
 63 {
 64     for(int i=a.l;i>0;i--)
 65     {
 66        a.a[i]<<=1;
 67        a.a[i+1]+=a.a[i]/inf;
 68        a.a[i]%=inf;
 69     }
 70     while(a.a[a.l]>0)a.l++;
 71     for(int i=b.l;i>0;i--)
 72     {
 73        b.a[i]<<=1;
 74        b.a[i+1]+=b.a[i]/inf;
 75        b.a[i]%=inf;
 76     }
 77     while(b.a[b.l]>0)b.l++;
 78 }
 79 int main()
 80 {
 81     scanf("%s%s",ch1+1,ch2+1);
 82     la=strlen(ch1+1);lb=strlen(ch2+1);
 83     if(la%9)a.l=la/9+1;
 84     else a.l=la/9;
 85     if(lb%9)b.l=lb/9+1;
 86     else b.l=lb/9;
 87     for(int i=1;i<=a.l;++i)
 88     {
 89         int k1=max(1,la-i*9+1),k2=la-(i-1)*9;
 90         for(int j=k1;j<=k2;++j)
 91             a.a[i]=a.a[i]*10+ch1[j]-'0';
 92     }
 93     for(int i=1;i<=b.l;++i)
 94     {
 95         int k1=max(1,lb-i*9+1),k2=lb-(i-1)*9;
 96         for(int j=k1;j<=k2;++j)
 97             b.a[i]=b.a[i]*10+ch2[j]-'0';
 98     }
 99     while(1)
100     {
101         if((a.a[1]%2==0)&&(b.a[1]%2==0)){diva();divb();cnt++;}
102         else if((a.a[1]%2==0))diva();
103         else if((b.a[1]%2==0))divb();
104         if(com()){a=sub(a,b);if(!a.l){while(cnt--)mul();print(b);break;}}
105         else {b=sub(b,a);if(!b.l){while(cnt--)mul();print(a);break;}}
106     }
107     return 0;
108 }

 

你可能感兴趣的:(gcd)