大數輾轉相除
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define Max 1000
bool compare(string n,string m)
{
int len1=n.length();
int len2=m.length();
if(len1<len2)
return false;
if(len1==len2)
{
for(int i=len1-1; i>=0; i--)
{
if(n[i]>m[i])
return true;
else if(n[i]<m[i])
return false;
}
}
return true;
}
int substract(int *p1,int len1,int *p2,int len2)
{
int i;
if(len1<len2)
return -1;
if(len1==len2)
{
for(i=len1-1; i>=0; i--)
{
if(p1[i]>p2[i])
break;
else if(p1[i]<p2[i])
return -1;
}
}
for(i=0; i<=len1-1; i++)
{
p1[i]-=p2[i];
if(p1[i]<0)
{
p1[i]+=10;
p1[i+1]--;
}
}
for(i=len1-1; i>=0; i--) //返回減法後a的長度
{
if(p1[i])
{
return (i+1);
return i;
}
}
return 0;
}
int division(char num1[],char num2[],char sum[])
{
int i,j;
int len1,len2;
int dvalue;
int ntemp;
int num_a[Max]= {0},num_b[Max]= {0};
len1=strlen(num1),len2=strlen(num2);
for(j=0,i=len1-1; i>=0; i--) //轉換數a
num_a[j++]=num1[i]-'0';
for(j=0,i=len2-1; i>=0; i--) //轉換數b
num_b[j++]=num2[i]-'0';
dvalue=len1-len2;
for(i=len1-1; i>=0; i--) //若450 3 ,會把3變成003,上面已反轉
{
if(i>=dvalue)
num_b[i]=num_b[i-dvalue];
else
num_b[i]=0;
}
len2=len1;
for(i=0; i<=dvalue; i++)
{
while((ntemp=substract(num_a,len1,num_b+i,len2-i))>=0)
{
len1=ntemp;
}
}
int x=0;
for(i=len1-1; i>=0; i--)
{
sum[x++]=num_a[i]+'0';
}
return len1;
}
int main()
{
int len;
char num1[Max],num2[Max];
char sum[Max],summ[Max]= {0};
cin>>num1>>num2;
if(!compare(num1,num2))
{
char num[Max];
strcpy(num,num1);
strcpy(num1,num2);
strcpy(num2,num);
}
len= division(num1,num2,sum);
if(len>0)
{
while(len>0)
{
len=division(num2,sum,summ);
strcpy(num2,sum);
strcpy(sum,summ);
memset(summ,0,sizeof(summ));
}
cout<<num2<<endl;
}
else if(len==0)
{
cout<<num2<<endl;
}
else
cout<<"1"<<endl;
return 0;
}