同余方程
形如a*x≡b(mod n)的式子称为线性同余方程。对于这样的式子有解的充要条件是gcd(a,n)|b.
于是扩展gcd求解
将原方程化为一次不定方程 a*y+n*y=b.
利用扩展欧几里得算法求解不定方程a * x + n* y = b的整数解的求解全过程,步骤如下:
1、先计算Gcd(a,n),若n不能被Gcd(a,n)整除,则方程无整数解;否则,在方程两边同时除以b/gcd(a,n),得到新的不定方程a’* x + n’* y = gcd(a,n).
2、利用扩展欧几里德算法求出方程a’* x + n’* y = 1的一组整数解x0,y0,则gcd(a,n)* x0,gcd(a,n)* y0是方程a’* x + n’ * y = gcd(a,n)的一组整数解;
3、根据数论中的相关定理,记k=b/gcd(a,n),可得方程a* x + n * y = b的所有整数解为:
x = k*x0 + n/gcd(a,n)* t
y =k* y0 –n/gcd(a,n)* t (t=0,1,2,……)
调整得到正整数解
注意因为解有多个,而我们要求最优解,所以(x+=n/gcd(a,n)%(n/gcd(a,n));
青蛙的约会
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;
long long init(){
long long rv=0,fh=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-') fh=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
rv=(rv<<