弱智从零开始学数学系列。。。
1.欧几里德算法
2.扩展欧几里德算法
3.exgcd解不定方程(ax+by=c)
写个板题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)//扩展gcd
{
ll r,t;
if(b==0)
{
x=1;y=0;
return a;
}
r=exgcd(b,a%b,x,y);
t=x;x=y;
y=t-a/b*y;
return r;
}
ll cal(ll a,ll b,ll c)//求解ax+by=c的x的最小整数解
{
ll x,y;
ll gcd=exgcd(a,b,x,y);
if(c%gcd!=0) return -1;
x*=c/gcd;b/=gcd;
if(b<0) b=-b;
return (x+b)%b;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
ll a,b;
while(~scanf("%lld%lld",&a,&b))
{
if(__gcd(a,b)!=1)
{
puts("sorry");
continue;
}
ll x=cal(a,b,1);
ll y=(1-a*x)/b;
printf("%lld %lld\n",x,y);
}
return 0;
}
4.exgcd解线性同余方程
板题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)//扩展gcd
{
ll r,t;
if(b==0)
{
x=1;y=0;
return a;
}
r=exgcd(b,a%b,x,y);
t=x;x=y;
y=t-a/b*y;
return r;
}
ll cal(ll a,ll b,ll c)//求解ax+by=c的x的最小整数解
{
ll x,y,ret,gcd;
gcd=exgcd(a,b,x,y);
if(c%gcd!=0) return -1;
x*=c/gcd;b/=gcd;
if(b<0) b=-b;
ret=x%b;
if(ret<=0) ret+=b;
return ret;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int T;
ll a,b;
scanf("%d",&T);
while(T--)
{
ll rev;
scanf("%lld%lld",&a,&b);
rev=cal(b,9973,1);
printf("%lld\n",a*rev%9973);
}
return 0;
}