gcd and ex_gcd(欧几里得算法和拓展欧几里得算法 )
辗转相除基本写法:(求两个数的最大公约数)
int gcd(int a,int b)
{
int c;
while(b)
{
c=a%b;
a=b;
b=c;
}
return
}
简化递归:
long long gcd(long long a,long long b)
{
if(b==0)return a;
return gcd(b,a%b);
}
简化:
return b ? gcd(a%b) : a ;
lcm求取(最小公倍数):
防止a,b溢出
gcd(素因子分解):
1.素因子分解;
2.gcd
3.lcm
代码实现:
附加(求解多个数的最大公约数):
LL work(LL a[],LL n)
{
LL ans=a[0];
int i;
for(i=1;i<n;i++)
ans=gcd(ans,a[i]);
return ans;
}
ex_gcd及逆元:
·扩展欧几里得算法:用来求ax+by=t方程的整数解。其中,t=gcd(a,b)。
模板:
void Ex_gcd(int a, int b, int &x, int &y)
{
if(b == 0)//递归出口
{ x = 1;
y = 0;
return;
}
int x1, y1;
Ex_gcd(b, a%b, x1, y1);
x = y1;
y = x1-(a/b)*y1;
}
或
void Ex_gcd(int a, int b, int &x, int &y)
{
if(b == 0)//递归出口
{x = 1;
y = 0;
return;
}
Ex_gcd(b, a%b, x, y);
int t;
t=x;
x =y;
y = t-(a/b)*y;
}
用ex_gcd计算逆元(x,y);
如果ax≡1(mod m),则称x为a在模m下的逆元,可以记作:a^−1。