对于正整数 ,有
所以便有了更相减损法。
int gcd(int a,int b)
{
while(a!=b)
{
if(a<b)swap(a,b);
a-=b;
}
return a;
}但是这个写法时间复杂度有一点点的大。
如何优化?
我们可以发现
- 当 、时
- 当 、时
- 当 、时
所以便有了二进制优化做法
int gcd(int a,int b)
{
int c=1;
while(a-b)
{
if(a&1 && b&1)
{
if(a>b)a=((a-b)>>1);
else b=((b-a)>>1);
}
else if(a&1)
{
b>>=1;
}
else if(b&1)
{
a>>=1;
}
else
{
c<<=1;
a>>=1,b>>=1;
}
}
return a*c;
}常数比 __gcd(a,b) 小