#include<iostream>
using namespace std;
bool isevent(int x){
return x%2==0?true:false;
}
int gcd(int x,int y){
if(x<y)
return gcd(y,x);//确保x>y
if(y==0)
return x;
else
{
if(isevent(x)) //x是偶数
{
if(isevent(y)) //判断y是否偶数
return (gcd(x>>1,y>>1)<<1); //x是偶数,y是偶数
else
return (gcd(x>>1,y));//x是偶数,y是奇数
} else //x是奇数
{
if(isevent(y))//y是偶数
return (gcd(x,y>>1));
else
return (gcd(y,x-y));//y是奇数
}
}<pre name="code" class="cpp">int gcd(int a,int b)
{
while(a!=b)
{
if(a>b)
a-=b;
else
b-=a;
}
return a;
}
}int main(){ int a,b; cout<<"请输入两个数(a,b):"<<endl; cin>>a>>b; cout<<gcd(a,b)<<endl; return 0;}
辗转相除法:
intgcd(inta,intb){
inttemp;
if(a<b){/*交换两个数,使大数放在a上*/
temp=a;
a=b;
b=temp;
}
while(b!=0){/*利用辗除法,直到b为0为止*/
temp=a%b;
a=b;
b=temp;
}
returna;
}
//更相减损法
int gcd(int a,int b)
{
while(a!=b)
{
if(a>b)
a-=b;
else
b-=a;
}
return a;
}