线性同余方程求解,可以把同余方程转化成线性丢番图方程,根据扩展欧几里德算法求出一组特解,然后再求出最小正整数解。
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL s1,s2,v1,v2,m;
long long extend_gcd(long long a,long long b,long long &x,long long &y)
{
if(a==0&&b==0) return -1;//无最大公约数
if(b==0)
{
x=1;
y=0;
return a;
}
long long d=extend_gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> s1 >> s2 >> v1 >> v2 >> m;
LL A,B,C;
A = v1-v2;
B = m;
C = s2 - s1;
LL gcd = __gcd(A,B);
if(C%gcd || v1 == v2)
{
cout << "-1" << endl;
return 0;
}
LL x,y;
LL d = extend_gcd(A,B,x,y);
x = x*(C/d);
LL mod = abs(B/d);
x = (x%mod + mod)%mod;
cout << x << endl;
return 0;
}